2016-09-06 58 views
2

我有兩個包含<h1>標記和複選框的div。我想在點擊特定div的複選框時檢索標題的值。例如:如何在該div內單擊複選框時獲取標題的值?

<div class="send"> 
    <h1>hi</h1> 
    <input type="checkbox" name="checkbox"/> 
</div> 
<div class="send"> 
    <h1>welcome</h1> 
    <input type="checkbox" name="checkbox"/> 
</div> 

如何獲得特定的標題值,當特定的複選框被點擊在特定的div在JavaScript中?誰能幫我嗎?

回答

3

$(':checkbox').change(function(){ 
 

 
if($(this).is(':checked')){ 
 

 
console.log($(this).prev('h1').text()) 
 

 
} 
 

 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="send"> 
 
    <h1>hi</h1> 
 
    <input type="checkbox" name="checkbox"/> 
 
</div> 
 
<div class="send"> 
 
    <h1>welcome</h1> 
 
    <input type="checkbox" name="checkbox"/> 
 
</div>

  1. 使用分組( 'H1'),以獲得檢查元素
1

的H1您需要change,而不是click作爲事件。在你的情況下,你可以使用prev(),因爲元素就在它之前。

$(".send input[type=checkbox]").change(function() { 
 
    console.log($(this).prev().text()); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="send"> 
 
    <h1>hi</h1> 
 
    <input type="checkbox" name="checkbox" /> 
 
</div> 
 
<div class="send"> 
 
    <h1>welcome</h1> 
 
    <input type="checkbox" name="checkbox" /> 
 
</div>

如果你只是想在value每當inputchecked你可以使用一個if裏面太:

$(".send input[type=checkbox]").change(function() { 
 
    if($(this).prop("checked")) { 
 
     console.log($(this).prev().text()); 
 
    } 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="send"> 
 
    <h1>hi</h1> 
 
    <input type="checkbox" name="checkbox" /> 
 
</div> 
 
<div class="send"> 
 
    <h1>welcome</h1> 
 
    <input type="checkbox" name="checkbox" /> 
 
</div>

0

您可以使用siblings()函數。

$("input:checkbox[name='checkbox']").click(function{ 
     if($(this).is(':checked')){ 
     var h1tagText = $(this).siblings("h1").text(); 
    } 
    }); 
0

純JavaScript解決方案:

var inputs = document.querySelectorAll(".send input[type=checkbox]"); 

for(var i = 0; i<inputs.length; i++){ 
    inputs[i].addEventListner("change",function(e){ 
    var heading = e.target.parentElement.querySelector("h2").innerHTML; 
    //do something with heading 
    }); 
} 
0

我猜你想,只有當該複選框被選中,而不是選中的值。
這是代碼:

$(document).ready(function(){ 
    $("input").click(function(){ 
     if($(this).is(":checked")){ 
      alert($(this).parent().find("h1").html()); 
     } 
    }); 
}); 
相關問題