可能很简单,但我不明白。我有这个代码:
var myNewHref = "#"+jQuery(this).attr('id');
jQuery(this).attr('href', myNewHref);
jQuery(this).attr("id", "");
在第一行中,我根据元素的 id 创建新变量。在第二行中,我添加了带有 myNewHref 变量的 href 属性。在第三行中,我将 id 设置为空。问题是,如果我将 id 设置为空,它也会更改 myNewHref 变量并使其为空,但我希望它仍然使用 myNewHref 设置。此外,清除 id 的操作是在我将其分配给我的 href 后发生的。有人可以帮忙吗?
最佳答案
似乎工作得很好:
<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>
关于JavaScript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19623697/