如何使用jQuery获取单击元素的html内容

Ola*_*eye 2 html javascript css jquery

我试图获得特别点击的div的内部html内容,我有很多div元素。

看下面我使用的代码。

$(function() {

    $( "#try" ).click(function() {
        var clickedValue = $(this).find('div').text();
        alert(clickedValue);
    });

});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

我想以某种方式做到这一点,即当单击具有蓝色背景色的div时出现B,但随后看来我的方式有问题。由于某些原因,我无法将id属性赋予这些div集,并且它们必须具有相同的类。

上面代码的问题是,当我单击6个div元素中的任何一个时,clickedvalue将为BRYBGW。

Aru*_*hny 5

$(this).find('div')将返回该div元素内的所有#try元素,而您只想定位已点击的对象div

您可以使用event.target

$(function() {
  $("#try").click(function(e) {
    var clickedValue = $(e.target).text();
    alert(clickedValue);
  });

});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


但我建议您使用点击处理程序来定位实际的子元素。...通过将处理程序直接绑定到它们或使用事件委托

$(function() {
  //or $("#try > div").click(function(e) {
  $("#try").on('click', 'div', function(e) {
    var clickedValue = $(this).html();
    alert(clickedValue);
  });

});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)