繁体   English   中英

jQuery如何使用$(this)获得被点击项的价值?

[英]Jquery how to use $(this) to get value of clicked item?

我无法获得我点击过的特定物品的价值

<html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $(this).click(function(){
            alert($(this).find("button").html());
        });
    });
    </script>
    </head>
    <body>
    <p>test 1</p>
    <p>test 2</p>
    <button>Yes</button>
    <button>No</button>
    </body>
    </html>
  • 我试过$(this).find("button").html() ,但是即使我单击了第二个按钮(“否”),它也会返回第一个按钮的值(“是”)。
  • $(this).find("p").html() ,将返回值1st

  • 如何使用$(this)获得我点击的项目的价值?
  • 不要建议我插入class或id,我不应该触摸html。
  • 请协助,谢谢。

这是因为$(this).click事件侦听器已添加到document对象,而不是任何特定的html元素。

$(document).ready(function(){
    $('button,p').on('click',function(){
        alert($(this).html());
    });
});

塞子: https ://jsfiddle.net/wx38rz5L/1743/

如果您试图在单击时获取每个按钮的html,请使用它。

  $('button').click(function () {
       alert($(this).html());
  });

this在点击处理程序始终是文件(你已经绑定的处理程序),这样就不会什么帮助。 相反,使用类似

$(document).click(function(e){
    if ($(e.target).is("button"))
        console.log($(e.target).text());
    } else {
        console.log("not clicked (directly) on a button");
    }
});

或只是

$(document).on("click", "button", function(e){
    console.log($(this).text());
});

绑定两个button上的click事件,并使用innerHTML获取html元素的内容。

  $(document).ready(function() { $('button').click(function(event) { alert(event.target.innerHTML); }); }); 
 <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> </head> <body> <p>test 1</p> <p>test 2</p> <button>Yes</button> <button>No</button> </body> </html> 

您必须检测哪个$(this)被绑定? 尝试这样的事情:

  1. 设置对象

<button class="btn red btn-xs editbtn" type="button" value="${rs.id}" value="${rs.id}">

  1. 该对象的功能

$(function(){ $('.editbtn').click(function(e){ common.showSpinner(); var idbbpdtd = $(this).val(); }); });

尝试这个。

        $(document).ready(function() {
            $(this).click(function(event) {
                    alert(event.target.innerHTML);
            });
        });

在jQuery中, event.target始终指触发事件的元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM