Setting for attribute of a label element with object oriented method

心不动则不痛 提交于 2019-12-22 09:46:50

问题


Labels have a 'for' attribute which makes them point to a certain input field. I need to change the value of this attribute with JQuery so I could use:

$("label").attr("for", "targetName");

But I also need to set the className, so i'd prefer to use:

$("label").attr({
    for: "targetName",
    className: "something" 
});

You might allready notice the problem, for is ofcourse a keyword in javascript. Does anybody know how I could solve this? Currently i'm using the first method to set the for and the second to set several other attributes, it works but it's not really pretty.

Any help would be greatly appreciated.


回答1:


you could also use htmlFor instead of for:

$("label").attr({
    htmlFor: "targetName",
    className: "something" 
});



回答2:


Have you tried using string keys:

$("label").attr({
  'for': "targetName",
  'className': "something"
});

?




回答3:


Try something like:

$("label").attr("for", "targetName").attr("class", "something")

OR

$("label").attr("for", "targetName").addClass("something")

OR

$("label").attr({ "for": "targetName", className: "something" });



回答4:


This should work,

$("label").attr("for","targetName").attr("class","something");


来源:https://stackoverflow.com/questions/1232579/setting-for-attribute-of-a-label-element-with-object-oriented-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!