我正在尝试获取特别点击的 div 的内部 html 内容,我有许多 div 元素。
看看我在下面使用的代码。
$(function() {
$( "#try" ).click(function() {
var clickedValue = $(this).find('div').text();
alert(clickedValue);
});
});
<div id="try">
<div class="cchoice" style="background-color: blue;">B</div>
<div class="cchoice" style="background-color: red;">R</div>
<div class="cchoice" style="background-color: yellow;">Y</div>
<div class="cchoice" style="background-color: black;">B</div>
<div class="cchoice" style="background-color: gray;">G</div>
<div class="cchoice" style="background-color: white;">W</div>
</div>
我想以这样的方式进行操作,即当单击背景颜色为蓝色的 div 时出现 B,但我的操作方式似乎有问题。由于某些原因,我不能为那些 div 集提供 id 属性,它们必须具有相同的类。
上面代码的问题是,当我点击 6 个 div 元素中的任何一个时,clickedvalue 将是 BRYBGW。
最佳答案
$(this).find('div')
将返回 #try
元素中的所有 div
元素,而不是你想要的仅针对点击的 div
您可以使用 event.target
$(function() {
$("#try").click(function(e) {
var clickedValue = $(e.target).text();
alert(clickedValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="try">
<div class="cchoice" style="background-color: blue;">B</div>
<div class="cchoice" style="background-color: red;">R</div>
<div class="cchoice" style="background-color: yellow;">Y</div>
<div class="cchoice" style="background-color: black;">B</div>
<div class="cchoice" style="background-color: gray;">G</div>
<div class="cchoice" style="background-color: white;">W</div>
</div>
但我建议使用点击处理程序来定位实际的子元素....通过直接将处理程序绑定(bind)到它们或通过使用事件委托(delegate)
$(function() {
//or $("#try > div").click(function(e) {
$("#try").on('click', 'div', function(e) {
var clickedValue = $(this).html();
alert(clickedValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="try">
<div class="cchoice" style="background-color: blue;">B</div>
<div class="cchoice" style="background-color: red;">R</div>
<div class="cchoice" style="background-color: yellow;">Y</div>
<div class="cchoice" style="background-color: black;">B</div>
<div class="cchoice" style="background-color: gray;">G</div>
<div class="cchoice" style="background-color: white;">W</div>
</div>
关于javascript - 如何使用 jQuery 获取点击元素的 html 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26541159/