我在PHP中构建一个表单,我有一个目前正常工作的字段:
<input type='text' name='Name' value='Name'/>
但我不希望用户必须手动擦除值,所以我这样做了:
<input type='text' name='Name' value='Name'
onblur="if(this.value==''){ this.value='Name'; this.style.color='#BBB';}"
onfocus="if(this.value=='Name'){ this.value=''; this.style.color='#000';}"
style="color:#BBB;" />
但很明显,因为这是在PHP中并且表单以$output="<form...
开头,因为"
所以我创建了这个:
<input type='text' name='Name' value='Name'
onblur='if(this.value==''){ this.value='Name'; this.style.color='#BBB';)'
onfocus='if(this.value=='Name'){ this.value=''; this.style.color='#000';}'
style='color:#BBB' />
哪个不会导致错误,但根本不起作用。我的意思是表单正确显示,但点击时值不会消失。所以我想把'
和onblur
中的onfocus
更改为"
,这在html中工作,但在php中提出了与以前相同的错误。那么这个解决方案是什么?
答案 0 :(得分:3)
转义引号:
$output = "<input type='text' name='Name' value='Name'
onblur=\"if(this.value==''){ this.value='Name'; this.style.color='#BBB';}\"
onfocus=\"if(this.value=='Name'){ this.value=''; this.style.color='#000';}\"
style='color:#BBB;' />";
答案 1 :(得分:1)
有一个非常简单的解决方案:使用HTML5占位符:
<input type="text" name="Name" placeholder="Name">
(这将自动比原始颜色更浅,因此此处不需要style
属性)
所有现代浏览器都支持此功能,如here所示。只有IE 9及更低版本不支持这一点,并且这些浏览器只占浏览器总使用量的5%,因此通常最好放弃对旧浏览器的支持,转而使用更轻松的功能。
答案 2 :(得分:0)
在'
例如:
<input type='text' name='Name' value='Name'
onblur='if(this.value==\'\'){ this.value=\'Name\'; this.style.color=\'#BBB';)'
答案 3 :(得分:0)
您可以使用反斜杠来转义字符串中的引号字符。例如:"…\"…"
或'…\'…'
。问题是这很容易变得难以阅读。 真正提高可读性的是使用HEREDOC语法:
$output = <<<_
<input type='text' name='Name' value='Name'
onblur="if(this.value==''){ this.value='Name'; this.style.color='#BBB';}"
onfocus="if(this.value=='Name'){ this.value=''; this.style.color='#000';}"
style="color:#BBB;" />
_;
您甚至可以在其中扩展变量,并且仍然可以使标记保持可读性。例如:
$output = <<<_
<div class="$c"><a href="$l">$t</a></div>
_;