开发者

jquery html parent

开发者 https://www.devze.com 2023-03-20 15:29 出处:网络
Lets say I have this code: <div class=\"user\"> <img class=\"profilepic\" src=\"someimage.jps\">

Lets say I have this code:

<div class="user">
    <img class="profilepic" src="someimage.jps">
    <div class="cleaner"></div>
    [ <a href="javascript:void(0);" id="skip" Onclick="javascript:chg_background();">change bg</a> ]
    <div class="cleaner" style="padding-bottom: 开发者_高级运维5px;"></div>
</div>

How can i change div class="user" with red background, with jquery parent method or similar?

Thanks!

Guns


You could use closest to walk back up the DOM tree:

function chg_background(el) {
    var $user = $(el).closest('.user');
    $user.css('background-color', '#f00');
}

And change the HTML to this:

<a href="javascript:void(0);" id="skip" Onclick="javascript:chg_background(this);">change bg</a>

Or do it in a more traditional jQuery fashion:

$('#id').click(function() {
    var $user = $(this).closest('.user');
    $user.css('background-color', '#foo');
});

And drop the onclick attribute on the #id link.

0

精彩评论

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