You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery代码点击a2类元素返回全部结果,如何获取单个被点击元素?

问题分析与解决方案

原代码的核心问题在于:

  • 内联onclick触发的on()函数里,重复给所有.a2元素绑定点击事件,逻辑冗余且混乱
  • $(".a2")会选择页面中所有带a2类的元素,调用text()自然会返回所有元素的文本内容

以下是两种可行的修改方案:

方案一:修改内联事件传递当前元素

直接在点击时把当前元素传给处理函数,无需重复绑定事件:

修改后的完整代码

<!DOCTYPE html>
<html>
<head>
    <title> Login Form in HTML5 and CSS3</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
</head>
<body>
<div class="a1" > <div class="a2" onclick="on(this)"> eq </div> </div>
<div class="a4" > <div class="a2" onclick="on(this)"> dwqr </div> </div>
   <p id="demo"> i am hare </p>

<script>
function on(el) {
    // el就是当前被点击的.a2元素
    document.getElementById("demo").innerHTML = $(el).text();
}
</script>
<style>
 .a1
 {
    width:310px;
    height:310px;
    border:2px solid red;
 }
 .a4
 {
    width:310px;
    height:310px;
    border:2px solid red;
 }
 .a2
 {
    width:200px;
    height:200px;
    border:2px solid red;
    padding-left: 50px;
    padding-top: 50px;
    padding-bottom: 50px;
    text-indent:-9999px;
 }
</style>
</body>
</html>

方案二:移除内联事件,使用jQuery事件绑定(推荐)

这种方式更符合jQuery的编码规范,避免内联事件的耦合:

修改后的完整代码

<!DOCTYPE html>
<html>
<head>
    <title> Login Form in HTML5 and CSS3</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
</head>
<body>
<div class="a1" > <div class="a2"> eq </div> </div>
<div class="a4" > <div class="a2"> dwqr </div> </div>
   <p id="demo"> i am hare </p>

<script>
// 页面加载完成后绑定事件
$(function() {
    $(".a2").click(function() {
        // $(this)指向当前被点击的.a2元素
        $("#demo").text($(this).text());
    });
});
</script>
<style>
 .a1
 {
    width:310px;
    height:310px;
    border:2px solid red;
 }
 .a4
 {
    width:310px;
    height:310px;
    border:2px solid red;
 }
 .a2
 {
    width:200px;
    height:200px;
    border:2px solid red;
    padding-left: 50px;
    padding-top: 50px;
    padding-bottom: 50px;
    text-indent:-9999px;
 }
</style>
</body>
</html>

两种方案的核心都是准确获取当前被点击的元素:方案一通过内联事件传递this,方案二通过jQuery事件回调里的$(this),这样就能只获取单个点击元素的文本内容。

内容的提问来源于stack exchange,提问作者Vasu devan gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 06:37:09