如何使用jquery动态获取单击的值?

时间:2015-05-11 01:08:01

标签: javascript jquery

我有以下代码,我正在尝试动态输出单击文本值和日期值。我不确定我做错了什么,点击后没有返回任何内容

HTML

!--- start dynamic bit  data violation type is will be dynmically generated by the server---->

<h3  id="toggle-next" data-violation-type="1111" class="violation"> lorm 1 violation 1</h3>
<div  id="moreinfo-231">

<p> lorem ipsum </p>
<p> lorem ipsum </p>
<p> lorem ipsum </p>

</div>
<!--- start dynamic bit---->
<!-- end dynamic bit-->
<h3  id="toggle-next" data-violation-type="11232" class="violation"> lorm 2 violation 2</h3>
<div id="moreinfo-232">

<p> lorem ipsum 2</p>
<p> lorem ipsum 2</p>
<p> lorem ipsum 2</p>

</div>
<!-- end dynamic bit-->

JQUERY

$(document).ready(function() {
$("#toggle-next").find("h3").click(function(){
            alert($(this).text());  

    console.log(" you have clicked " +$(this).text());  
 console.log(" you have clicked data " +$(this).data("violation-type"));            
                            });




});

2 个答案:

答案 0 :(得分:0)

你不需要.find(),因为它是相同的元素。

$(document).ready(function() {
  $("#toggle-next").click(function() {
    var clicked = $(this);
    alert(clicked.text());  
    console.log(" you have clicked " + clicked.text());  
    console.log(" you have clicked data " + clicked.data("violation-type"));            
  });
});

如果您多次使用对象,那么缓存对象也是一个好主意,在这种情况下,您使用$(this) 3次,因此每次都必须在DOM中查找它。

此外,您应该将#toggle-next更改为.toggle-next并将其设为class="toggle-next"而不是id="toggle-next"。你只允许每页有1个ID,jQuery会停止查找它。

答案 1 :(得分:0)

元素的ID必须是唯一的,因此您需要使用该类来选择所有这些目标h3元素。在您的情况下,所有h3元素都具有类violation,因此请使用它。

$(document).ready(function() {
  $("h3.violation").click(function() {
    alert($(this).text());
    console.log(" you have clicked " + $(this).text());
    console.log(" you have clicked data " + $(this).data("violation-type"));
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
!--- start dynamic bit data violation type is will be dynmically generated by the server---->

<h3 id="toggle-next" data-violation-type="1111" class="violation"> lorm 1 violation 1</h3>

<div id="moreinfo-231">
  <p>lorem ipsum</p>
  <p>lorem ipsum</p>
  <p>lorem ipsum</p>
</div>
<!--- start dynamic bit---->
<!-- end dynamic bit-->

<h3 id="toggle-next" data-violation-type="11232" class="violation"> lorm 2 violation 2</h3>

<div id="moreinfo-232">
  <p>lorem ipsum 2</p>
  <p>lorem ipsum 2</p>
  <p>lorem ipsum 2</p>
</div>
<!-- end dynamic bit-->

您的选择器还有另一个问题,即#toggle-nexth3元素,因此$("#toggle-next").find("h3")不会返回任何elemnet