简体   繁体   中英

Setting for attribute of a label element with object oriented method

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.

Have you tried using string keys:

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

?

Try something like:

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

OR

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

OR

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

you could also use htmlFor instead of for:

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

这应该工作,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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