如何在使用jQuery时为占位符设置onblur和onfocus字符串

How to set onblur and onfocus string for placeholder when using jQuery

本文关键字:设置 占位符 onblur 字符串 onfocus jQuery      更新时间:2023-09-26

我已经尝试动态更新我的html,到目前为止,它正在将文本区域添加到页面中,但我定义的onblur和onfocus行为并不是因为在onblr和onfocu属性上包含了双引号。我的代码如下:

$('#answerList').append('<li><div class="row"><div class="eight columns"><textarea id="answerswerText" name="answerswerText" 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以使这些属性工作

"(双引号)无法转义''(单引号)。但是其中作为单引号可以转义双引号。

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

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

快乐编码:)

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

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

Fiddlehttp://jsfiddle.net/aD38E/

包含连续双引号是个问题,这是正确的。简单的修复方法是用反斜杠转义双引号,如下所示:

onfocus="this.placeholder = '"'""

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

这是一个正在工作的JSFiddle:http://jsfiddle.net/ud36Y/

或者您可以使用以下代码:

$('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"]')