javascript - jQuery 每个函数都会迭代所有内容,尽管 if 语句

标签 javascript jquery

单击页面上的特定链接后,代码会附加页面 URL。当我运行代码时,它会按预期执行,仅将 URL 附加到与代码匹配的链接。然而,当我打印到控制台时,我注意到它似乎对页面上的每个链接都执行此操作,尽管 if 语句应该限制它。当我去掉 if 语句时,代码的功能是一样的。然而,即使它有效,我想让它更有效率,并且只在与参数匹配的链接上运行。

 // Function to change the link by adding the current page
 function setSlateLink() {
     // get the URL of the current page
     var currentPage = document.location.href;
     // get the URL of the slate
     var slateLink = jQuery('a[href$="code=magic"]').attr("href");
     // rewrite the slate, adding the query string with a key for Slate and value of the current page
     console.log("Processing link change");
     return slateLink += "&sys:interaction:summary=" + currentPage;

 }

 jQuery(document).ready(function() {

     jQuery("a").each(function(i, item) {
         // if there is an a tag, check that it ends like this
         if (jQuery(i == 'a[href$="code=magic"]')) {
             console.log("Found link: " + jQuery("a").attr("href"));
             // change the link to set the referrer (current page) in the URL
             jQuery('a[href$="magic"]').attr("href", setSlateLink());
             console.log("Changed link");
         }

     });
 });

知道什么会导致这种情况吗?

最佳答案

你调用if (jQuery(i == 'a[href$="code=magic"]'))
这会返回一个 true 的 jquery 对象,导致 if 语句始终执行。

如果您想查看该元素是否与选择器匹配,您可以使用 jquerys #is 方法:
if ($(item).is('a[href$="code=magic"]'))

关于javascript - jQuery 每个函数都会迭代所有内容,尽管 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31170288/

相关文章:

javascript - JSP 页面上 jQuery 验证插件的多个实例

javascript - 导航栏特定的 jQuery 滚动动画

jquery - 为什么 jQuery 会删除我的 DIV 中的内容以及如何阻止它这样做?

javascript - 我应该如何更改我的 jquery 脚本以在第一次单击时为移动菜单设置动画?

javascript - 表单数据未验证

javascript - 在 JavaScript 中启用和禁用超链接

javascript - 未捕获的类型错误 : Cannot read property 'hasAttribute' of undefined

javascript - 如何使用服务器端验证生成客户端验证?

javascript - 悬停时,如何使用 jQuery 动画更改多个属性

javascript - 给没有id的div添加id