简体   繁体   English

jQuery在任何点击时重置textarea,但据说只有当textarea具有特定值时才会这样做

[英]jQuery resets textarea on any click, but is said to only do so when the textarea has a certain value

I'm currently experiencing a problem. 我目前遇到了问题。 I'm trying to reset my textarea, if it has the value Message... (which it has when you load the page). 我正在尝试重置我的textarea,如果它有值Message... (当你加载页面时它有)。 But as it is now, it resets no matter what value it has. 但就像现在一样,无论它具有什么价值,它都会重置。 Here's my jquery code: 这是我的jquery代码:

if ($("#text").value = 'Message...') 
{
    $("#text").click(function () {
        $(this).val('');
    });
}

The HTML code is just a textarea inside a form. HTML代码只是表单中的textarea。

$("#text").value = 'Message...' will always be true because you're using the assignment operator. $("#text").value = 'Message...'将始终为true,因为您正在使用赋值运算符。 use === instead for comparison. 使用===代替进行比较。

if ($("#text").val() === 'Message...') 
{
    $("#text").click(function () {
        $(this).val('');
    });
}

A few of your problems are that 你的一些问题是这样的

if ($("#text").value = 'Message...') 
// should be replaced with the line below
if ($(this).val() == 'Message...')

Notice the use of val() instead of value and instead of the assignment operator, I used the equality operator (you could also the identity operator === ). 注意使用val()而不是value而不是赋值运算符,我使用了相等运算符(你也可以使用identity运算符=== )。

Also, the reason why your text is always being reset is because your event handler is resetting the text each time you click the #text element, so to achieve the expected behavior you need to wrap the logic inside the event handler. 此外,文本始终被重置的原因是因为每次单击#text元素时,事件处理程序都会重置文本,因此要实现将事务处理程序中的逻辑包装起来所需的预期行为。

$("#text").click(function () {
  if ($(this).val() == 'Message...')
    $(this).val('');
 });

If you wanted to achieve a "placeholder" effect you could use the following instead: 如果您想获得“占位符”效果,可以使用以下代码:

$("#text").focusin(function () {
  if ($(this).val() == 'Message...')
    $(this).val('');
}).focusout(function() {
  if ($(this).val() == '')
    $(this).val('Message...');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM