1

What is the best way to add an attribute to an <input /> on focus using js / jQuery?

Right now, off the top of my head, I would think

$(document).ready(function(){
    $('input').focus(function(){
        $(this).attr(attributeHere);
    });
});

Is that correct? Does the attribute have to have quotes around it?

Right now, it is just going to be an attribute with no value. Value will be added later.

4

3 回答 3

2

在我看来很好。我要补充的只有一件事是,即使您想将属性留空,您也应该给它一个空字符串作为值。

var attrName = 'someAttr';
$(this).attr(attrName,'');

通过不传递值(即使是空字符串),您实际上是在为您真正想要调用 setter 的属性调用 getter 函数。

于 2013-05-01T17:06:19.233 回答
2

这是你可以做的:

$(document).ready(function(){
    $('input').on("focus",function() {
        $(this).attr('name', 'value'); // value could be '' if you would like to specify it later.
    });
});

我希望它有所帮助。

于 2013-05-01T17:09:20.240 回答
1

你需要这样做——

$(this).attr('attributeName','attributeValue');

您正在尝试.attr(attributeName)用于访问属性值

描述:获取匹配元素集中第一个元素的属性值。

请参阅 api:

http://api.jquery.com/attr/

.attr( attributeName, value )

attributeName
Type: String   <--  Either a var containing string or an "string" 
The name of the attribute to set.

value
Type: String or Number
A value to set for the attribute.
于 2013-05-01T17:07:06.690 回答