0

我对 JavaScript/jQuery 不是很好,并且在完成一项非常基本的任务时遇到了很多麻烦。我有一个img,当点击时,应该给我div它所在的父级的 id。

这是标记:

<div id="client-1">
    <img src="~/Content/plus.ico" alt="plus" onclick="ButtonExpandClick()" />
</div>

这是javascript:

<script type="text/javascript">
    function ButtonExpandClick() {
        alert($(this).parent().attr("id"));
    }
</script>

单击图像会给我一个提示“未定义”的警报,但是div当我检查页面时,我可以清楚地看到它的 id 为“client-1”。我必须在这里遗漏一些简单的东西。我也尝试过使用.closest以及传递this给函数,但没有运气。谢谢你的帮助!

4

6 回答 6

3

不要将onclick属性用于事件。您正在使用 jQuery,“正确”绑定事件。

向图像添加一个类:

<img src="~/Content/plus.ico" alt="plus" class="icon" />

然后绑定事件:

$(function(){
    $('.icon').click(function(){
        alert($(this).parent().attr("id"));
    });
});
于 2013-07-29T20:37:35.567 回答
1

如果您使用 jQuery 连接 click 事件而不是内联,那么您将this自动获得传入的事件:

请注意,您必须为图像提供一个id或为其找到另一个选择器。

jQuery(document).ready(function() {
    jQuery("#myImg").click(ButtonExpandClick);
});
于 2013-07-29T20:37:33.210 回答
0

你需要传入 this

onclick="ButtonExpandClick(this)"

JS

function ButtonExpandClick(elem) {
   alert($(elem).parent().attr("id"));
}

声明内联事件也是一个坏主意。使用 javascript 直接附加事件。

<script>

   $(function() {
       $('#client-1 img').click(function() {
           alert($(this).parent().attr("id"));
       });
   });

</script>
于 2013-07-29T20:36:00.843 回答
0

您必须使用 jquery.click 或发送带有功能的元素。像发送我(这个)。

于 2013-07-29T20:36:48.940 回答
0

你可以使用这样的东西:

$(function() {
    $('img').on('click', function(e) {
            var id = this.parentNode.id; //Using javascript to access id is faster.
        alert(id);
    });
});

在Jsfiddle工作的示例

建议将此图像放在容器中。并将其更改为。这对性能更好。

$(函数(){

   var images = $('#container').find('img');
   images.on('click', function(e) {
        var id = this.parentNode.id; //Using javascript to access id is faster.
        alert(id);
    });

});
于 2013-07-29T20:43:57.227 回答
0

更简单的是,您可以尝试使用绑定:

<div id="client-1">
  <img src="~/Content/plus.ico" alt="plus"  />
</div>

<script>
  $(function() {
    $('img').on('click', function(){
      // Two ways to do the same thing
      alert(this.parentNode.id);
      alert($(this).parent()[0].id);
    });
  });
</script>
于 2013-07-29T20:52:25.157 回答