HTML Onclick with $(this)

2019-03-06 03:13发布

问题:

I have a conflict with calling the general jQuery click function and so I need to call an onclick event on the HTML element itself while still being able to use $(this)

$('.item-main-section, .item-status').click( function () {
        var slideHeight = $(this).parent().children('.item-slide-section').height();
        if ($(this).parent().height() > 50) {
            $(this).parent().animate({height: '50px'}, 300);
            $(this).parent().children('item-slide-section').animate({bottom: '0px'}, 300);
        } else {
            $(this).parent().animate({height: slideHeight + 50 + 'px'}, 300);
            $(this).parent().children('item-slide-section').animate({bottom: slideHeight - 5 + 'px'}, 300);
            $(this).parent().siblings('.item-wrapper').animate({height: '50px'}, 300);
            $(this).parent().siblings('.item-wrapper').children('item-slide-section').animate({bottom: '0px'}, 300);
        }
    });

Instead of the jquery click i need onclick="thisFunction()" on the elements but if I get rid of the first line I lose the ability to use $(this). It's hard to explain but I hope it makes sense to someone.

回答1:

you can pass this element as parameter:

onclick="thisFunction($(this));"

and on function recieve it as element:

function thisFunction(element)
{
  $this = element;
  //use it here
}