addAttr 在 jquery 中不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10407622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:17:02  来源:igfitidea点击:

addAttr not working in jquery?

jquery

提问by Hai Truong IT

I have a sample code :

我有一个示例代码:

<input type="text" name="color" id="color" value="" />

And jquery

和 jquery

$('#color').change(function(){
    $('#color').addAttr('value', 'test');
});

When I change value in textbox is result value=""and error in firebug $("#color").addAttr is not a function

当我更改文本框中的值时value="",萤火虫中的结果和错误$("#color").addAttr is not a function

How to fix it ?

如何解决?

回答by BoltClock

It's called .attr(), not .addAttr().

它被称为.attr(),不是.addAttr()

You should also replace your inner $('#color')with $(this)to indicate that you're manipulating the same input that's being changed:

你也应该更换你的内心$('#color')$(this)以表明你正在操纵多数民众赞成被改变相同的输入:

$('#color').change(function(){
    $(this).attr('value', 'test');
});

回答by Oscar Jara

You are confused about removeAttr()and you think that addAttr()exists, that's wrong.

你很困惑removeAttr(),你认为addAttr()存在,那是错误的。

The function you want is .attr()- nowadays .prop(), I believe.

你想要的功能是.attr()- 现在.prop(),我相信。

回答by Sudhir Bastakoti

You could also do:

你也可以这样做:

$('#color').change(function(){
    $(this).val('test');
});