如何在这个textarea中逃脱,以便onblur和onfocus工作?

时间:2013-07-18 16:48:26

标签: javascript html escaping

我的Codepen:http://codepen.io/leongaban/pen/jqEwF

下面的textarea包含一些javascript,用于在用户点击时清除文本,如果用户没有输入任何内容,则将默认文本放回。

我需要转义以便javascript可以正常工作

我已经尝试'而只是',当我在textarea(onfocus)内部点击时,文本不会消失,我在控制台中收到此错误:
enter image description here

然而,当我尝试"它会起作用!但我需要'而不是"

<div id="the-accept-textarea">
    <textarea id="accept-response-text" rows="5" cols="50"
    value="I’d be happy to make this introduction if possible. Contact me at your convenience."
    onblur="if (this.value == '') {
    this.value = 'I’d be happy to make this introduction if possible. Contact me at your convenience.';}"
    onfocus="if (this.value == 'I’d be happy to make this introduction if possible. Contact me at your convenience.')
    {this.value = '';}">I’d be happy to make this introduction if possible. Contact me at your convenience.
    </textarea>
</div>

你会如何处理?


更新 尝试这个

var defaultValue = 'I\'d be happy to make this introduction if possible. Contact me at your convenience.'
var txtArea = document.getElementById("accept-response-text");
console.log('txtArea = '+txtArea);
console.log(defaultValue);
txtArea.value = defaultValue;

txtArea.focus = function() {
    console.log('inside focus');
    if (this.value === this.defaultValue) {
        console.log('value is defaultValue');
        this.value = '';
    }
}
txtArea.blur = function() {
    if (this.value === '') {
        this.value = this.defaultValue;
    }
}

然而焦点和模糊不起作用,但它是通过Javascript设置值到textarea

<textarea id="accept-response-text" rows="5" cols="50" value=""></textarea>

3 个答案:

答案 0 :(得分:1)

您可以使用\

转义它们
if (this.value == '') {
    this.value = 'I\'d be happy to make this introduction if possible. Contact me at your convenience.';
}

答案 1 :(得分:1)

你需要的只是

Live Demo

window.onload=function() {
  var txtArea=document.getElementById("accept-response-text");
  txtArea.onfocus=function() {
    if (this.value === this.defaultValue) {
      this.value = '';
    }
  }
  txtArea.onblur=function() {
    if (this.value === '') {
      this.value = this.defaultValue;
    }
  }
}

更新

这是一个带占位符的版本,支持没有占位符的浏览器

Live Demo

function hasPlaceHolder() {
  var i = document.createElement('input');
  return 'placeholder' in i;
}    
window.onload=function() {
  var txt_area_accept = document.getElementById("accept-response-text");
  if (!hasPlaceHolder()) {
    txt_area_accept.defaultValue=txt_area_accept.getAttribute("placeholder");
    txt_area_accept.onfocus = function() {
      if (this.value === this.defaultValue) {
        this.value = '';
      }
    }
    txt_area_accept.onblur = function() {
      if (this.value === '') {
        this.value = this.defaultValue;
      }
    }
  }
}    

答案 2 :(得分:1)

您在更新中发布的代码是正确的,除了添加您分配给on​focuson​blur的事件,而不仅仅是focusblur

那就是说,你应该使用placeholder属性而不是你当前正在使用的属性。