27

我有一个示例代码:

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

和jQuery

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

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

如何解决?

4

3 回答 3

53

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

您还应该将您的内部替换$('#color')$(this)以表明您正在操作正在更改的相同输入:

$('#color').change(function(){
    $(this).attr('value', 'test');
});
于 2012-05-02T04:17:44.893 回答
17

你对此感到困惑removeAttr(),你认为它addAttr()存在,那是错误的。

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

于 2012-05-02T04:21:50.587 回答
5

你也可以这样做:

$('#color').change(function(){
    $(this).val('test');
});
于 2012-05-02T04:21:00.527 回答