如果字段为空,则回显占位符
我有一个输入,我想在其中放入占位符文本,但仅当它的相应值是空字符串。文本框中应输入的值是从 PHP 数组中回显的,但如果该值为空,则应回显占位符。目前,我有这样的代码:
<?php echo sponsorData('address0') == '' ? 'Address Line 1' : 'Other'; ?>
sponsorData()
只是从数组中获取内容;唯一的论点是关键。这里重要的一点是它返回一个字符串。
这段代码给出了奇怪的行为;我得到类似 Hello worldAddress Line 1
的内容,其中 Hello world
是用户输入的文本,而 Address Line 1
显然是占位符。奇怪的是,占位符在提交时被存储到数组中。
我的问题是:有人可以对我的三元运算符进行更正吗?或者,如果这不起作用,请告诉我执行内联 if
语句(blegh)?
谢谢
I have an input that I'd like to put a placeholder text in, but only if it's respective value is an empty string. The value that should go in the textbox is echoed from a PHP array, but if this value is empty, the placeholder should be echoed instead. At the moment, I've got this code:
<?php echo sponsorData('address0') == '' ? 'Address Line 1' : 'Other'; ?>
sponsorData()
just gets stuff from an array; it's only argument is the key. The important bit here is it returns astring.
This code gives odd behaviour; I get stuff like Hello worldAddress Line 1
, where Hello world
is the user typed text and Address Line 1
is obviously the placeholder. Strangely, the placeholder gets stored into the array on submission.
My question is this: can someone offer a correction of my ternary operator or, if that won't work, tell me to do an inline if
statement (blegh)?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试以下代码:
felix
try the following code:
felix
您遇到了运算符优先级问题。尝试:(
将三元运算符语句放在括号中)。
You're running into operator precedence issues. Try:
(put brackets around the ternary operator statement).
你似乎工作正常,我不认为错误在那里。我将这样做:
You seem to have this working ok, I don't think the error lies there. Here is how I would do it:
您必须考虑到
sponsorData('address0')
可能有空格,因此您可以添加trim
函数,如下所示:You have to consider that the
sponsorData('address0')
may have spaces, so you can add thetrim
function, like this: