gpt4 book ai didi

jquery - 我可以使用 jquery 来清空文本区域字段或像输入框一样的 ajax 吗?

转载 作者:行者123 更新时间:2023-12-01 03:52:04 24 4
gpt4 key购买 nike

我总是在工作中使用这个片段:

<input type="text" onblur="if (this.value=='') { this.value='your email'; }" onfocus="if (this.value == 'your email') { this.value=''; }" value="your email" /> 

基本上,它会显示一个以“您的电子邮件”为值的文本框,当单击文本输入框时 - 该值变为空白..因此他们输入他们的电子邮件..如果他们不输入电子邮件,它就会重置回“您的​​电子邮件”。

我想对 textarea 执行此操作或类似操作并将其转换为 jQuery(也是 jQuery 中的上述代码)?

<textarea name="msg">Message:</textarea><br />

最佳答案

这应该可以解决问题:

适用于输入和文本区域 - 无论您为每个区域设置什么默认值都将保留。按原样使用。

请参阅此处的 fiddle :http://jsfiddle.net/leifparker/DvqYU/2/

(这会提取数据属性中的默认值并将其存储)

HTML

<textarea>I love bananas ..</textarea>
<textarea>How about you?</textarea>
<input type="text" value="Time for a bath ..">
<input type="text" value=".. because I smell">

JS

$('textarea, input[type=text]')
.each(function(){
$(this).data('defaultText', $(this).val());
})
.focus(function(){
if ($(this).val()==$(this).data('defaultText')) $(this).val('');
})
.blur(function(){
if ($(this).val()=='') $(this).val($(this).data('defaultText'));
});

<小时/> 编辑:

ANeves 提出了一种替代方案,它利用了 HTML5 placeholder 属性,如下所示。如果您不关心旧浏览器,您可以单独使用 占位符 HTML(它可以在 native 运行,结果与上面的 JS 类似),否则,如下所示,您将需要添加一个JS后备。

在这里摆弄:http://jsfiddle.net/leifparker/DvqYU/14/

HTML

<textarea placeholder="A few words about yourself"></textarea>
<textarea placeholder=".. and a few more about your mangy cat."></textarea>
<input type="text" placeholder="Your Awesome City">
<input type="email" placeholder="rickastin@youjustgot.com">

JS

function hasPlaceholderSupport() {
var input = document.createElement('input');
return ('placeholder' in input);
}

if (!hasPlaceholderSupport()){
$('textarea, input[type=text], input[type=email]')
.each(function(){
if ($(this).val()=='') $(this).val($(this).attr('placeholder'));
})
.focus(function(){
if ($(this).val()==$(this).attr('placeholder')) $(this).val('');
})
.blur(function(){
if ($(this).val()=='') $(this).val($(this).attr('placeholder'));
});
}

关于jquery - 我可以使用 jquery 来清空文本区域字段或像输入框一样的 ajax 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7557801/

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