gpt4 book ai didi

javascript - 如何在此文本区域中转义 ’ 以便 onblur 和 onfocus 起作用?

转载 作者:行者123 更新时间:2023-11-30 12:59:34 24 4
gpt4 key购买 nike

我的代码笔:http://codepen.io/leongaban/pen/jqEwF

下面的文本区域包含一些 javascript,用于在用户单击时清除文本,并在用户未键入任何内容时恢复默认文本。

我需要转义 ' 以便 javascript 能够工作

我已经尝试了 '',当我在文本区域 (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 id="accept-response-text" rows="5" cols="50" value=""></textarea>

最佳答案

你只需要

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;
}
}
}
}

关于javascript - 如何在此文本区域中转义 ’ 以便 onblur 和 onfocus 起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17729474/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com