如何使用jQuery获取非特定DIV元素的内容

I've a problem and I hope that it's possible to explain.

I have a lot of short texts which come from a mysql-DB.

while ($foo = mysql_fetch_object($query)) {
  $text = $foo -> column_text_db;
  echo '<div class="atextdiv">' . $text . '</div>';
  }

now i want to add an onclik-Event-Handler to the "atextdiv"-Container(s) who takes the content and put it on an input-field:

<form>
<input type="text" id="clickcontent" />
</form>

My problem: Each page has a different number of records in database. The final HTML-Code (after parsing the PHP-Code) could be:

 <div id="wrapper">
 <div class="atextdiv">Papa was a rolling stone</div>
 <div class="atextdiv">Oh my god! They killed Kenny</div>
 <div class="atextdiv">Foo Bar</div>
 <!-- more content -->
 </div>
 <form>
 <input type="text" id="clickcontent" />
 </form>

So, how can I get the content of each "atextdiv"-Container after click on it?

3个回答



您可以在'。atextdiv'</ code>上绑定click事件,并在事件中使用。text() </ p>

  $('#wrapper')。  on('click','。asxtdiv',funnction(){
$(“#clickcontent”)。val($(this).text())
})
</ code> </ pre>

</ div>

展开原文

原文

You can bind click event on '.atextdiv' and in event fetch its value using .text()

$('#wrapper').on('click', '.atextdiv', funnction(){
    $("#clickcontent").val($(this).text())
})

drb88830
drb88830 理想情况下,您应该绑定到比文档更近的共同祖先。
6 年多之前 回复



就像:</ p>

  $(“。atextdiv”)。click(function)  (){
console.log($(this).text());
});
</ code> </ pre>

使用 this <的组合 / code>和点击处理程序中的 .text </ code>方法。</ p>
</ div>

展开原文

原文

Just like:

$(".atextdiv").click(function() {
    console.log($(this).text());
});

Use a combination of this and the .text method inside the click handler.



只需获取发生点击事件的项目的innerHTML:</ p>

  $('。atextdiv')。click(function(e){
alert(e.currentTarget.innerHTML);
})
</ code> </ pre>

http://jsfiddle.net/9VE6A/8/ </ p>
</ div>

展开原文

原文

Just grab the innerHTML of the item that the click event is occurring on:

$('.atextdiv').click(function(e){
    alert(e.currentTarget.innerHTML);
 })

http://jsfiddle.net/9VE6A/8/

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问