【问题标题】:Javascript, get the name of a clicked buttonJavascript,获取点击按钮的名称
【发布时间】:2014-03-14 07:19:49
【问题描述】:

试图获取已点击按钮的 id 或名称。但是当我尝试访问按钮的 id 或名称时,我只会在弹出窗口中收到一条未定义的消息。有人可以为我指明正确的方向以使其正常工作吗?

<!DOCTYPE html PUBLIC "-//W2C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Testing : Buttons</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>

<div id="buttons" style="width:100%;height:100%">
    <p id="custom_buttons" >
    </p>
</div>

<div id="footer">
</div>

<script type="text/javascript">
$(function() {
    var datasetPresets = ["Python", "Java", "C++"];
    var datasetPresetsContainer = $("#custom_buttons");
    $.each(datasetPresets, function(index, value) {
        datasetPresetsContainer.append("<button class=std_buttons value=" + value + ">" + value + "</button>");
    });

    $("button.std_buttons").click(function () {
        var button = $(this);
        alert(button.id);
    });

});

</script>
</body>
</html>
</html

【问题讨论】:

  • alert(this.id) 可以。
  • alert(button.attr('id'));
  • 感谢这里的答案,我意识到我的变量不是命名为“id”,而是“value”。所以,现在它可以工作了。谢谢。

标签: javascript jquery


【解决方案1】:

基本上,试试

警报(this.id);

而不是

alert(button.id);

但是这个问题显示了最少的研究工作,因为这里已经回答了多次,一个简单的搜索就足够了:

How to get ID of button user just clicked?

Getting the ID of the element that fired an event

Get id of element on button click using jquery

how to get the id when a certain button is clicked using jquery

【讨论】:

  • 谢谢。我已经阅读了许多其他主题,还有更多。但是我错过了一件事,我的变量没有命名为“id”,而是命名为“value”。因此,显然无论我尝试什么都行不通。所以问的原因,不是因为缺乏搜索,而是因为缺乏js/jq经验。这里的答案告诉我它应该可以工作,所以必须有其他错误。然后我发现了错误。
【解决方案2】:

在纯 javascript 中,你会做这样的事情

$("button.std_buttons").click(function (event) {
    var button = event.target;
    alert(button.id);
});

在此处阅读有关事件对象的更多信息https://developer.mozilla.org/en/docs/Web/API/Event

【讨论】:

    【解决方案3】:

    您需要使用attr() 来获取按钮的id,因为button 是一个jQuery 对象:

    alert(button.attr('id');
    

    或者你可以保留你的选择器,但不要将其转换为 jQuery 对象:

    var button = this;
    alert(button.id);
    

    【讨论】:

      【解决方案4】:

      你只是使用attr(),属性是在jquery中使用attr("property name")访问的

      button.attr('id');
      

      或者只是

       $(this).id
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多