【问题标题】:How to set onblur and onfocus string for placeholder when using jQuery使用jQuery时如何为占位符设置onblur和onfocus字符串
【发布时间】:2013-09-03 06:13:33
【问题描述】:

我已经尝试动态更新我的 html,并且到目前为止它正在工作,以便将 textarea 添加到页面中,但是我定义的 onblur 和 onfocus 行为不是由于我认为在onblur 和 onfocus 属性。我的代码如下:

$('#answerList').append('<li><div class="row"><div class="eight columns"><textarea id="answerText" name="answerText" placeholder="Your answer here..."  onfocus="this.placeholder = """ onblur="this.placeholder = "Your answer here...""></textarea></div><div class="four columns"><input type="checkbox" name="correctCheckbox" id="correctAnswerCheckbox' + answerPosition + '" value="' + answerPosition + '"/><label for="correctAnswerCheckbox' + answerPosition + '">Correct Answer</label></div></div></li>');

当我通常只对 HTML 进行编码时,我使用以下内容:

<textarea id="questionText" name="questionText" placeholder="Your question here..." onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your question here...'"></textarea>

如何修复 javascript 以使这些属性正常工作

【问题讨论】:

  • placeholder 属性与您定义的相同。聚焦时,它的值变为空,而模糊时,它的值恢复原样。
  • 你为什么要改变焦点和模糊的占位符?占位符属性应该已经负责在焦点和模糊上切换文本。
  • 是的,我真的知道它更多地要做字符串形成,我在输入 html 时使用单引号作为字符串,但是在添加时会导致问题
  • 这是 IE10 中的一个错误,适用于 textarea 的所有其他浏览器,解决方法仅针对此
  • 您的目标到底是什么?因为正如 Barry 提到的,这些是由 html5 本身处理的

标签: javascript jquery string append


【解决方案1】:

""(双引号)不能转义''(单引号)。但是单引号可以转义双引号。

在您的情况下,我想如果您仍然需要转义在双引号内指定的单引号,然后使用反斜杠 ()。

<textarea id="questionText" name="questionText" placeholder="Your question here..." onfocus="this.placeholder = \'\'" onblur="this.placeholder =\ 'Your question here...\'"></textarea>

快乐编码:)

【讨论】:

  • 感谢这解决了编译器问题,但仍然无法使用指定的占位符和行为 onfocus 和 onblur 按预期附加文本区域
  • 你能不能把它选为“答案”,这样这个问题就可以从 SO 中关闭,它会减少来自 SO 的未决问题的数量 :)
【解决方案2】:

如果我理解了你的问题,这个字符串可能会对你有所帮助。

'<textarea id="questionText" name="questionText" placeholder="Your question here..." onfocus="this.placeholder = \'\'" onblur="this.placeholder = Your question here..."></textarea>'

小提琴http://jsfiddle.net/aD38E/

【讨论】:

  • 当我动态附加 html 时,我仍然无法让 onfocus 和 onblur 工作,我的字符串在 html 中的格式正确我想我的报价仍然有问题使用 \' 作为 onfocus 和 onblur 文本的开始和结束
【解决方案3】:

您是正确的,包含连续的双引号是问题所在。简单的解决方法是用反斜杠转义双引号,如下所示:

onfocus="this.placeholder = \"\""

onblur="this.placeholder = \"Your answer here...\""

这是一个有效的 JSFiddle:http://jsfiddle.net/ud36Y/

【讨论】:

  • 另外,这里有一个 Fiddle 以更 jQuery 友好的方式展示你的功能。这种编写 jQuery 的方法也解决了您的多个嵌套引号问题。 jsfiddle.net/XZc4f/5
  • 这似乎在 IE10 中对我有用;你能更具体地描述一下你的经历吗?
【解决方案4】:

或者你可以使用这个代码:

$('input[type="text"]').focus(function () {
    $(this).data('placeholder', $(this).attr('placeholder'))
        .attr('placeholder', '');
}).blur(function () {
    $(this).attr('placeholder', $(this).data('placeholder'));
});

// $('textarea') or $('input[type="email"]')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-02
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 2018-12-18
    • 2019-01-03
    • 2012-03-10
    相关资源
    最近更新 更多