问题描述:

JQUERY

$(document).ready(function(){

$("div").click(function(){

var pars = $("p");

for( i=0; i<pars.length; i++ ) {

alert("Found paragraph: " + pars[i].innerHTML);

});

});

CSS

.container {

padding:10%

}

[class*="col-"] > div {

background:white;height:200px;width:200px;

padding:20px;

margin:13%;

}

.value {

position: absolute;

top: 90px;

left: 130px;

}

HTML

<div class="container">

<div class="row">

<div class="col-md-4 col-sm-5">

<div style="background-color:pink"><h1 id="test" class="value">1</h1></div>

</div>

<div class="col-md-4 col-sm-5">

<div style="background-color:pink" ><h1 id="test" class="value">2</h1></div>

</div>

<div class="col-md-4 col-sm-5">

<div style="background-color:yellow" ><h1 id="test" class="value">3</h1></div>

</div>

<div class="col-md-4 col-sm-5">

<div style="background-color:yellow"><h1 id="test" class="value">4</h1></div>

</div>

<div class="col-md-4 col-sm-5">

<div style="background-color:blue"><h1 id="test" class="value">5</h1></div>

</div>

<div class="col-md-4 col-sm-5">

<div style="background-color:blue" ><h1 id="test" class="value">6</h1></div>

</div> `

Every time I click a box I want to display an alert with the number that is within the box.

How can I solve this problem?

网友答案:

Dimitar Popov is right to suggest using alert($(this).find(".value").html()); and adding it do a click handler.

You shouldn't add a handler to all <div>s, though. Instead, only target those divs that correspond with the squares :

$(document).ready(function(){
    $('[class*="col-"] > div').click(function(){
        alert($(this).find(".value").html());
    });
});

See this Fiddle for a working demo. I also made a few other minor improvements to your code there...

网友答案:

When you are attaching listeners, you get the DOM element, for which the event has happened with this. So in your case the code for alerting the value of every h1 when the corresponding div is clicked is:

$(document).ready(function(){ $("div").click(function(){
alert($(this).find(".value").html());
});
相关阅读:
Top