使jQuery函数仅在特定的div id或类中运行

时间:2013-07-26 03:35:11

标签: jquery

我有一个jQuery函数来更改网页上的 href 。如何使此脚本仅在#container div中运行?

$('a[href*="example.com"]').each(function(){
 var index = this.href.indexOf(".com/");
 this.href = this.href.slice(0, index+5)
})

我试过了,

$('#container').$('a[href*="example.com"]').each(function(){
 var index = this.href.indexOf(".com/");
 this.href = this.href.slice(0, index+5)
})

但它不起作用。上面的代码出了什么问题?

1 个答案:

答案 0 :(得分:2)

使用.find()

$('#container').find('a[href*="example.com"]').each(function(){
    var index = this.href.indexOf(".com/");
    this.href = this.href.slice(0, index+5)
})

或使用descendant selector

$('#container a[href*="example.com"]').each(function(){
    var index = this.href.indexOf(".com/");
    this.href = this.href.slice(0, index+5)
})

您也可以尝试稍微不同的版本

$('#container').find('a[href*="example.com"]').attr('href', function(idx, href){
    var index = href.indexOf(".com/");
    return href.slice(0, index + 5)
})
相关问题