开发者

Issue with changing an attribute with jquery

I'm having an issue with changing the attribute for an id and can't seem to figure out what I'm doing 开发者_JAVA百科wrong. I guess it doesn't help that I'm new to this also.

I have a function that tests to make sure that I am pulling the correct id from the row in my form that I have dynamically created. It goes something like this:

myFunction() {
  var id = $(id).attr("id");
  alert("This is my id " + id);
}

This works with no problem and when I click the button assigned to alert me of my id it will give me the id of the dynamic row in my form. The issue is now when I try to change the id with this:

changeId() {
  var newId = $(id).attr("id", "x");
  alert("This is my new id " + newId);
}

What happens in this case is that it will alert saying "This is my new id [object Object]" instead of giving me the new id. Any suggestions? I'd really appreciate any help with this.


.attr(attribute, value) returns the jQuery object again (so you can keep chaining), if you want that assigned ID, you need to do this:

changeId() {
  var newId = $(id).attr("id", "x").attr("id");
  alert("This is my new id " + newId);
}

Though the direct route is much better, for example:

changeId() {
  var newId = "x"
  $(id).attr("id", newId);
  alert("This is my new id " + newId);
}


You are setting, and not getting.The jQuery object is returned when you use .attr to set an attribute - not the value you have set it to. Try:

changeId() {
  $(id).attr("id", "x");
  var id = $(id).attr("id");
  alert("This is my new id " + newId);
}


attr(name, value) returns a jQuery object. This is to support jQuery method chaining.

You want

changeId() {
  // ------------------------------v method chaining!
  var newId = $(id).attr("id", "x").attr("id");
  alert("This is my new id " + newId);
}

or simply

changeId() {
  $(id).attr("id", "x");
  alert("This is my new id " + id.id);
}

Maybe you also find a nicer name for the variable than id.


Running .attr() with one argument returns the value of the attribute.

Running .attr() with two arguments returns the jQuery object against which it was called.

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


attr when used to set an attribute returns the original jQuery object not the new attribute value.


Just change the id property of the DOM node. Works in all browsers and couldn't be simpler:

var el = document.getElementById("your_id");
el.id = "new_id";
alert(el.id);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜