特定链接的Jquery点击事件

4

我在Visual Studio ASP.net中使用Jquery。 我正在尝试在页面上特定图像链接(class =“button notice buttonEight”)被单击时显示消息。 这是页面代码的一部分:

<li class="levelOne"><a class="button notice buttonEight" href="#">
      <img src="<%= Page.ResolveUrl("~/PBS-Intranet/_res/_images/icon_notice.png") %>"/></a></li>
</ul>
<div class="endCap">
</div>

<script type="text/javascript">
    $(document).ready(function() {
        $("icon_notice").click(function() {
            var src = $(this).attr('src');
            alert("Hello world!");
        });
    });
</script>
6个回答

3

您需要告诉jQuery您正在单击什么,计算机不知道$("icon_notice")是什么。将id icon_notice添加到图像中,然后使用$("#icon_notice")进行选择,该代码应该可以很好地工作。


谢谢,你说得对。我需要给图片添加一个ID,现在一切都正常了! - jre247
很高兴能帮忙!您介意将问题标记为已回答,以便未来的谷歌搜索者参考吗? - Whetstone
...这就是我 :) 太棒了! - swdev

2
$(".notice").click(function() {
   alert("Hello world!");
});

如果只有一个标签使用 notice 类,那么这样做是可行的。但如果不是,它会将点击事件附加到每个具有 notice 类的标签上。使用 a.notice 会更具体,但仍可能存在问题。 - jtfairbank

0
如果您给图像一个ID,就可以使用id选择器符号“$(#<id here>)”在jQuery中引用它。
<a class="button notice buttonEight" href="#">
   <img id="icon_notice" src="<%= Page.ResolveUrl("~/PBS-Intranet/_res/_images/icon_notice.png") %>" />
</a>

<script type="text/javascript">
 $(document).ready(function() {
    $("#icon_notice").click(function () {
    var src = $(this).attr('src');
    alert("Hello world!");
    });
});

</script>

0

我不确定你遇到了什么问题。你可以使用链接的任何类来选择它:

$(document).ready(function() {
    $(".buttonEight").click(function() {
        alert("foo");
    });
});

0
你可以尝试这个。
$(document).ready(function(){
  $("a.notice").click(function(){
    alert("You clicked me.");
  });
});

0

你应该更改选择器以基于类 (或 id) 进行选择。基于 CSS 类进行选择时,语法为 .classname (注意类名前的点号)。

要选择具有多个类的元素,语法为 .classone.classtwo

在您的情况下,您可以使用如下内容:

$('.buttonEight').click(function()
{
   //your awesome code goes here.
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接