JavaScript 变量

标签 javascript variables

可能很简单,但我不明白。我有这个代码:

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

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

最佳答案

似乎工作得很好:

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>

关于JavaScript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19623697/

相关文章:

javascript - 如何使用 ajax 请求发送 Twitter OAuth 访问 token ?

swift - 如何在swift中使用来自不同类的变量?

javascript - 通过 php 和 jQuery 验证电子邮件

javascript - AngularJS - 在文件输入上将图像加载到 img 标签

javascript - 验证年龄字段

javascript - 压缩两个数组Javascript

php - Yii 2 : Can I access a variable in a view that's rendered by another view?

javascript - JQuery 算术变量被视为字符串

java - 如何将变量递增到字母表中的下一个或上一个字母?

java - GC 和在 for 循环中赋值