JQuery: assign an interactive event to multiple divs with similar identifier

I am working on a site that displays multiple entries. Each entry can be expanded / collapsed, showing more / less information. The HTML for each entry is as follows:

<div id="entry-1"><div>some text</div><div><img></div></div>
<div id="entry-2"><div>some text</div><div><img></div></div>
<div id="entry-3"><div>some text</div><div><img></div></div>

1,2,3 in "entry- {1,2,3}" is the identifier of each message. How to associate a click event with each div?

I tried to do:

$('div[id^="entry-"]').click( myFunc($(this)) ) ;

But when I click, nothing happens, the click does not work, even if JavaScript is loaded when the page loads.

+3
source share
5 answers

The problem is the keyword this. In this code ...

$('div[id^="entry-"]').click( myFunc($(this)) );

... this DOM, , ().

:

$('div[id^="entry-"]').click(function() {
     myFunc($(this));
});

@JCOC, .
myFunc($(this)) , click().

, undefined, , :

$('div[id^="entry-"]').click(undefined);

... .

+6

$('div[id^="entry-"]').click( myFunc($(this)) ) ;

$('div[id^="entry-"]').click( function(){ myFunc($(this)); } ) ;
+6

, , , . :

$('div[id^="entry-"]').click( myFunc ) ;

function myFunc(){
   var some = $(this);
   ...
}

, :

<div id="entry-1" class="entry"></div>
<div id="entry-2" class="entry"></div>
//JS Selector:
$("div.entry")

, :

$('div.entry').click( myFunc );
+5

, myFunc(), . . :

http://jsfiddle.net/sYWwK/

div, :

$('div[id^="entry-"]').click( function() {
        console.log( $(this) );
    }); 
+3

You are currently attaching a click listener to each individual entry. The best way to do this would be to attach the click recipient to the parent element of the posts. So, if we have the following HTML:

<div id="entries">
  <div id="entry-1"><div>some text</div><div><img></div></div>
  <div id="entry-2"><div>some text</div><div><img></div></div>
  <div id="entry-3"><div>some text</div><div><img></div></div>
</div>

JavaScript will look something like this:

$('#entries').click(function (e) {
  if (e.target.id.match('entry')) {
    var entry = $(e.target);
    // logic for show more/less
  }
});

If you went along the route that other people suggested and used classes for each entry, JavaScript would look like this:

$('#entries').click(function (e) {  
  if (e.target.className.match('entry') || $(e.target).parents('.entry').length) {
    var entry = $(e.target);
    // logic for show more/less
  }
});
0
source

Source: https://habr.com/ru/post/1791386/


All Articles