【问题标题】:Changing " to ' in PHP - HTML Form在 PHP 中将 " 更改为 ' - HTML 表单
【发布时间】:2015-01-15 16:35:49
【问题描述】:

我正在用 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="&lt;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' />

这不会通过错误,但根本不起作用。我的意思是表单正确显示,但点击后该值不会消失。所以我想将onbluronfocus中的'更改为",这在html中有效,但在php中出现了与以前相同的错误。那么解决这个问题的方法是什么?

【问题讨论】:

  • 您从 ' 开始 onblur,然后在其中使用 '。如果你这样做,而不是简单地使用点击事件或函数,那么你需要转义你的引号。在谷歌搜索会解释你如何。

标签: php html forms


【解决方案1】:

转义引号:

$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;' />";

【讨论】:

    【解决方案2】:

    有一个非常简单的解决方案:使用 HTML5 占位符:

    <input type="text" name="Name" placeholder="Name">
    

    (这会自动比原来的颜色更浅,所以这里不需要style属性)

    所有现代浏览器都支持这一点,如 here 所示。只有 IE 版本 9 及更低版本不支持此功能,并且这些浏览器仅占所有浏览器使用量的 5%,因此通常最好放弃对旧版浏览器的支持,转而支持让您的生活更轻松的功能。

    【讨论】:

    【解决方案3】:

    '之前使用反斜杠

    例如:

    <input type='text' name='Name' value='Name' 
        onblur='if(this.value==\'\'){ this.value=\'Name\'; this.style.color=\'#BBB';)'
    

    【讨论】:

    • 你的意思是反斜杠 (\) - 斜杠是 (/)
    • @ProgrammingStudent 我认为您需要转义其他引号。这将导致您的 JavaScript 代码出错。除非您将其放在 PHP 代码中的引号之间,否则反斜杠根本没有任何作用。
    【解决方案4】:

    您可以使用反斜杠来转义字符串中的引号字符。例如:"…\"…"'…\'…'。问题是这很容易变得难以阅读。 真正提高可读性的是使用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>
    
    _;
    

    【讨论】:

      猜你喜欢
      • 2019-08-29
      • 2018-11-15
      • 1970-01-01
      • 2023-04-11
      • 2018-10-28
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 2021-12-01
      相关资源
      最近更新 更多