【问题标题】:JQuery Get ID of clicked linkJQuery获取点击链接的ID
【发布时间】:2017-02-02 21:57:01
【问题描述】:

我的 HTML 中有这种类型的链接:

图书馆:

<script type="text/javascript" src="../../resources/js/jquery/jquery-1.12.3.min.js"></script>

HTML:

<a id='1' href='#' class='bulletinLink'> Bulletin du 11-01-2015 </a>
<a id='2' href='#' class='bulletinLink'> Bulletin du 13-02-2015 </a>
...

我想在点击时获取此链接的 id,这是我的 jQuery:

$(function() {
$('.bulletinLink').on('click',function(event){
    var id = $(this).attr('id');
    alert(id);
})
});

当我点击链接时,它不会触发 jQuery 函数,我错过了什么?

【问题讨论】:

  • “我无法访问 jquery 功能”是什么意思?
  • 你的代码是正确的,你遇到了什么问题?
  • 尝试一些输出。在函数的开头打印一些东西,也许还打印 $(this)。代码应该可以工作。确保完全调用了您的函数(封闭的函数)。 (编辑标点符号)
  • 我的意思是警报方法没有被调用
  • 检查控制台是否有任何 js 错误。确保包含 jquery 库

标签: javascript jquery


【解决方案1】:

您可以使用以下简化版本,您可以使用this.id 为您的DOM 检索属性id 而无需重新查询它。

PS:确保你have included jQuery in your page。 示例:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

$(function() {
  $('.bulletinLink').on('click', function(event) {
    alert(this.id);
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id='1' href='#' class='bulletinLink'> Bulletin du 11-01-2015 </a><br>
<a id='2' href='#' class='bulletinLink'> Bulletin du 13-02-2015 </a>

【讨论】:

  • 我正在使用这个版本:
  • @Pasja95 可能您在包含 jQuerym 时遇到问题,可能路径错误。尝试使用 CDN
【解决方案2】:

以下代码运行良好

$(function() {
  $('.bulletinLink').on('click', function(event) {
    alert($(this).attr("id"));
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id='1' href='#' class='bulletinLink'> Bulletin du 11-01-2015 </a><br>
<a id='2' href='#' class='bulletinLink'> Bulletin du 13-02-2015 </a>

【讨论】:

  • @Henak 抱歉,但是为什么你需要使用 $(this) 的 DOM? IMO 真的没有必要。
【解决方案3】:

你需要添加 jQuery 库...

使用这个:

&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

    猜你喜欢
    • 2012-11-28
    • 2016-08-15
    • 1970-01-01
    • 2019-05-06
    • 2011-07-27
    • 2012-12-31
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    相关资源
    最近更新 更多