首页 > 解决方案 > Replace name attr with current name + another string with jQuery?

问题描述

I have this code:

var prodElem = $('#dropTitle').text();

$(prodElem).clone(true, true).appendTo('#orders')
 .attr("name", $(this).attr("name") + "-1");

but the name attribute is being replaced by -1.

How can I utilize "this" in order to achieve the current name and append -1 to the end?

Thanks!

标签: javascriptjquery

解决方案


this in that code doesn't refer to the element(s) you're setting the name on. My guess is this code is running where this refers to window, and so $(this).attr("name") returns the window name (which is usually blank), so you're setting name on all of those elements to "" + "-1", which is of course, "-1".

You can use the version of attr that accepts a callback:

$(prodElem).clone(true, true).appendTo('#orders')
  .attr("name", function() {
    return $(this).attr("name") + "-1";
  });

There, this refers to each matching element.

Side note: If this is really the name attribute, it's reflected by the property name, so you could also do it with prop and get the reflected attribute directly in the function:

$(prodElem).clone(true, true).appendTo('#orders')
  .prop("name", function() {
    return this.name + "-1";
  });

推荐阅读