1

可能这很容易,但我无法弄清楚。我有这个代码:

var myNewHref = "#"+jQuery(this).attr('id');
jQuery(this).attr('href', myNewHref);
jQuery(this).attr("id", "");

在第一行中,我根据元素的 id 创建新变量。在第二行中,我添加了一个带有 myNewHref 变量的 href 属性。在第三行中,我将 id 设置为空。问题是,如果我将我的 id 设置为空,它也会更改 myNewHref 变量并使其为空,但我希望它仍然使用 myNewHref 设置。此外,清除 id 的操作发生在我将其分配给我的 href 之后。任何人都可以帮忙吗?

4

3 回答 3

1

似乎工作得很好:

http://jsfiddle.net/4y2HM/4/

<a href="#" id="test">hello</a>

<script>
    $('#test').click(function(){
        var myNewHref = "#"+$(this).attr('id');
        $(this).attr('href', myNewHref);
        $(this).attr("id", "");
        alert("href: " + $(this).attr('href'));
        alert("id: " + $(this).attr('id'));
    });
</script>
于 2013-10-27T21:20:31.663 回答
0

除非我多次运行代码,否则我无法复制您的问题。但是,要正确清除 ID,您可以简单地使用:

this.id = null;

您需要确保该代码不会多次运行。如果您的代码运行不止一次,那么您的 ID 将已被删除,您的href属性将设置为 just #。如果您的代码位于基于该特定元素的事件处理程序中,您可以使用jQuery 的one()函数仅处理该事件一次。

于 2013-10-27T21:25:15.347 回答
-1

如果您想摆脱该id属性,请使用以下方式:

jQuery(this).removeAttr("id");
/* Or */
this.removeAttr("id");

或者,如果你想取消id,你可以使用:

this.id = null;
于 2013-10-27T21:19:14.760 回答