简体   繁体   中英

Undefined when trying to use addClass on $(this) anchor tag

 function showImage(imageSrc) { $('a.slideTabLinkBlock').removeClass('active'); alert($(this).attr('class')); $(this).addClass('active'); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="slideTabLinkBlock" onclick="showImage('<?php echo $image_src; ?>');">Link</a>

I'm trying to add a class "active" when a link is clicked:

<a class="slideTabLinkBlock" onclick="showImage('<?php echo $image_src; ?>');"></a>

function showImage(imageSrc) {

    $('a.slideTabLinkBlock').removeClass('active');
    alert($(this).attr('class'));
    $(this).addClass('active');

}

When I alert $(this).attr('class') it displays "undefined".

Why am I not able to target the anchor tag with $(this)?

How can I add the "active" class to the link that is clicked?

When using a proper event handler you can store your $image_src variable eg in a data -attribute.

 $('.slideTabLinkBlock').on('click', function() { var $this = $(this), imgSrc = $this.data('imgsrc'); $('a.slideTabLinkBlock').removeClass('active'); $this.addClass('active'); alert($(this).attr('class')); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="slideTabLinkBlock" data-imgsrc="<?php echo $image_src; ?>">Link</a>

Because you are not providing any additional code I don't know why you are using an inline function in the anchor tag. Because you could normally do this:

$('a.slideTabLinkBlock').on('click',function(){
    var className =  $(this).attr('class');

    alert(className);
})

$(this) is refering to the Window object and thus not what you expect to be. You can pass "this" to the function inside the inline JS call, and create a jQuery element of the argument. See the snippet:

 function showImage(element, imageSrc) { $('a.slideTabLinkBlock').removeClass('active'); alert($(element).attr('class')); $(element).addClass('active'); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="slideTabLinkBlock" onclick="showImage(this, '<?php echo $image_src; ?>');">Link</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM