这是我网页上各种链接的格式。链接可以是以下任何类型:
<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/