javascript - 无法向 jQuery 中的链接添加属性?

标签 javascript jquery

这是我网页上各种链接的格式。链接可以是以下任何类型:

<a data-id="1444709976-ohgusB" data-toggle="modal" class="modal-link store-link" 
   href="http://firstwebsite.com/some-text.html" 
   data-target="#myModal">
   BOLDR Voyage watch may just be the “clever” device you want and need</a>

<a data-id="1443322807-iLmF2d" class="store-link" 
   href="http://secondwebsite.com/other-text.html" target="_blank">
   Gmail for Android: 7 cool tips and tricks you must try<span class="fa fa-external-link"></span></a>

我尝试使用以下 jQuery 来更改所有只有 .store-link 类的链接的属性。这是我的代码:

if($('a.store-link').hasClass('modal-link')==false){
  $(this).removeAttr('target');
  $(this).addClass('modal-link');
  $(this).attr('data-toggle','modal');
  $(this).attr('data-target','#myModal');
}

但是,任何链接的属性都没有变化。我也没有收到任何错误。

最佳答案

当你使用 each 时,它会在所有 a.store-link 上循环并且它会起作用, 在你的代码上你有一些错误,比如 $(this) ,我认为你认为它指的是 $("a.store-link") 但它不是

$('a.store-link').each(function()
{
   if($(this).hasClass('modal-link') == false)
   {
      $(this).removeAttr('target');
      $(this).addClass('modal-link');
      $(this).attr('data-toggle','modal');
      $(this).attr('data-target','#myModal');
   }
});

关于javascript - 无法向 jQuery 中的链接添加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33106856/

相关文章:

javascript - 为什么 replace() 会干扰 onclick()?

jquery - Spring Controller 的 JSON 响应未得到解析

javascript - 为&lt;script&gt;标签添加动态头参数值,用于加载js文件

javascript - 使用函数构建 ES6 模板字面量

javascript - 检查 div 的长度(不包括空格)

javascript - 通过 JavaScript 嵌入 Instagram

javascript - 减少 Angular JS 中的分页加载时间

javascript - 将标签输入保存在数组中并在重新打开时显示

php - 使用 Javascript 的交互式 HTML 表单

jquery - 如何在 jquery mobile 中将弹出窗口定位在屏幕顶部或固定在顶部?