开发者

Setting an attribute from a parents attribute

开发者 https://www.devze.com 2023-03-29 13:29 出处:网络
I have this HTML and i am trying to convert the href from photo.php to #photo etc for each <ul id=\"menu\">

I have this HTML and i am trying to convert the href from photo.php to #photo etc for each

<ul id="menu">
    <li id="home" class="tab_selected"><a href="home.php">Home</a></li>
    <li id="portfolio"><a href="portfolio.php">开发者_运维技巧;Portfolio</a></li>
    <li id="music"><a href="music.php">Music</a></li>
    <li id="video"><a href="video.php">Video</a></li>
    <li id="photo"><a href="photo.php">Photo</a></li>
</ul>

I have been trying something like this:

$('#menu li a').attr('href', "#"+$(this).parent().attr('id'));

But the href always comes out undefined.

I am storing the hash in the li#id but if i could not do this it would be even better.

Thanks.


$(this) does not refer to the object you think it refers to.

With .attr you can use a function as a second argument to compute new attribute values for each matched element, like this:

// i == index, val == value of href at index i
$('#menu li a').attr('href', function(i, val) {
    return '#' + $(this).parent().attr('id');
});

In the above example, this refers to the correct context (the currently iterated anchor element).

You can try it here.


All jQuery

$('#menu li a').each(function () {
    var a = $(this);
    a.attr('href', "#" + a.parent().attr('id');
});

Part jQuery

$('#menu li a').each(function () {
    this.href = "#" + $(this).parent()[0].id;
});

Less Part jQuery

$('#menu li a').each(function () {
    this.href = "#" + this.parentNode.id;
});

Take your pick :)


The problem is that this doesnt holds the wrong value (it refers to any wrapping context there may be), because you're not in the proper context. Look at either of the (currently) 3 other answers to see how to get around this issue (hint, you want to use each)


$('#menu li a').each(function(){
    var $this = $(this);
    $this.attr('href', "#"+$this.parent().attr('id'));
});
0

精彩评论

暂无评论...
验证码 换一张
取 消