0

I'm adding some code(!with js code included!) dynamically.

<div class="r"></div>
<script>
    //Here is code that dinamiccaly add another div into div.r
    //Example:
    //<div class="w"><img src="a.png"><div class="i">Some Text</div></div>
    $('.r').on('click', $('.w'), function (e) {
        console.log($(this).children($('.i')).text());
    });
</script>

Problem that this click event works anythere I click in div.w and returns text of ALL div.w combined in one string without spaces (sometext1sometext2).

Sorry if I wrote something wrong. I'm bad in english.

SoundOfTheSky
  • 99
  • 1
  • 10

2 Answers2

3

Event delegation is wrong. You are using a jQuery collection

$('.r').on('click', $('.w'), function (e) {
                    ^^^^^^^

where it should be just a selector

$('.r').on('click', '.w', function (e) {
                    ^^^^
epascarello
  • 204,599
  • 20
  • 195
  • 236
1

The selector has to be of type string. Look at the following:

$('.r').on('click', '.w', function (e) { 

from documentation of on

seethrough
  • 712
  • 4
  • 15