简体   繁体   中英

Am I using 'this' correctly? jQuery

I am working on a click event - where it hides any users that are not the same value as the one clicked on. This is a snippet of the relevant HTML.

<div class="main">
        <section class="tweets">
        <div class="tweet">
           <p class="time">Sun Mar 15 2020 20:04:53 GMT-0700 (Pacific Daylight Time)</p>
           <p class="users" data="sharksforcheap">@sharksforcheap: </p>
           <p class="message">last night i formulated a life #sxsw</p></div>

When I manually input the value of the users value in my :contains it works fine. I'll click on sharksforcheap for example and it will hide every other users that are not of that.

    $('.tweets').on('click', '.users', function(){

      var user = $(this).data('users');
      $('.tweet').not(':contains(sharksforcheap)').hide(); 
    });

However, I want to obviously make it work for any users that I click on as hard-coding it for each user is not feasible. So I made a var called user and referenced it to this which should hold the data of my users . However, this doesn't work.

     $('.tweets').on('click', '.users', function(){

      var user = $(this).data('users');
      $('.tweet').not(':contains('+ user + ')').hide(); 
    });

Am I using this incorrectly in this context?

This is how you need to specify data-users attribute to get its value with .data("users") :

<p class="users" data-users="sharksforcheap">@sharksforcheap: </p>

But it seems that what you need is easier achieved with

$('.tweet').not($(this).closest('.tweet')).hide();

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