A Jquery click function for multiple divs

Trying to use one click function for all of my div boxes. Did some research but still not able to get it working correctly. I'm new to programming so I might be going about this the wrong way, here is an example of what I'm trying to do:

<div id="test_1">
  <p class="example">display this text 1</p>
</div>

<div id="test_2">
  <p class="example">display this text 2</p>
</div>

<div id="test_3">
  <p class="example">display this text 3</p>
</div>
$('div[id^="test"]').each(function(){
    $(this).click(function(){
        test = $(this).parent().find('.example').attr("p")
        alert(test)
    })
})

I thought this would work but if I click on div test 2 or 3 the alert shows "display this text 1" instead of "display this text 2" or "...3" .

Any idea what I'm doing wrong?

Remove .parent() . Otherwise you're getting all the nested .example elements, and retrieving the .attr('p') of the first one.

$('div[id^="test"]').each(function(){
    $(this).click(function(){
        var test = $(this).find('.example').attr("p")
        alert(test)
    })
})

Or shortened like this:

$('div[id^="test"]').click(function(){
    var test = $(this).find('.example').attr("p")
    alert(test)
})

Your question shows that you're getting a proper text result, though your code shows .attr("p") , which would not. I've left it the way it was to keep the code example the same.

我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章