3

I have a jQuery function to change the href on a webpage. How do I make this script only run inside the #container div?

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

I've tried this,

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

but it doesn't work. What's wrong with the code above?

4

1 回答 1

2

使用.find()

$('#container').find('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)
})

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

$('#container').find('a[href*="example.com"]').attr('href', function(idx, href){
    var index = href.indexOf(".com/");
    return href.slice(0, index + 5)
})
于 2013-07-26T03:37:50.550 回答