jQuery - 如果链接具有特定 ID,则 if 子句运行函数

标签 jquery

如果单击的链接是 artist_link,我需要运行脚本。我需要这样做的原因是因为我有一个历史 api 脚本,并且如果单击此链接,则需要运行该脚本。它在页面加载时运行,但由于历史 api ajaxes 在内容中,因此没有页面加载。

这就是我所拥有的;

if ($('a').attr('id') == 'artist_link'){ alert ('hello'); }

好吧,我应该解释一下。它必须是一个 if 子句,因为只有 IF 单击的链接具有该特定 ID,脚本才会运行。该子句位于 AJAX 请求中,该请求是我的历史 API 脚本的一部分。

$.ajax({
    url: url,
    type: 'GET',
    dataType: "html",
    success: function (responseData) {

        $("#main").hide().html($("#load", responseData)).fadeIn(500); //fadeIn new page
        if (url =='Home'){
         $.ajax({
         type: "GET",
         url: "AJAX/request_feed.js",
         dataType: "script"
         });
        }
        if (url =='Discover'){

         $.ajax({
         type: "GET",
         url: "AJAX/get_artists.js",
         dataType: "script"
         });

         }

         if ($('a').attr('id') === 'artist_link'){ alert ('hello'); }   
    },
    error: function (jqXHR, textStatus, errorThrown) {
        window.location.replace("404");
    }
});

更新:

此外,单击函数位于历史脚本的开头,因此我只需要确定单击的 a 是否具有该特定 ID

$(document).on("click", "a", function (event) {

最佳答案

I need to run a script if a link clicked is artist_link

那么只针对 ID 并设置点击功能有什么问题吗?

$("#artist_link").on('click', function() {
    alert('hello');
});

编辑:

$(document).on("click", "a", function (event) {
   //do ajax stuff here
   if (event.target.id=='artist_link') {
       //do some stuff if the right link was clicked ...
       //make sure you don't redefine the event, and it will be available in
       //the ajax functions scope as well (as long as it's inside the click function)
   }
});

关于jQuery - 如果链接具有特定 ID,则 if 子句运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13129670/

相关文章:

javascript - JS 按组对数组值进行分组

javascript - 使用 jquery 将匹配的单词包装在链接中

javascript - 两个 div 同时设置动画

javascript - 将 JSON HTML 字符串转换为 HTML

jquery - Yii2:验证屏蔽输入

javascript - 检查是否选择了 optgroup 中的部分或全部选项

jQuery 多选无法通过单击事件删除选项

jquery - 受字体类型影响的文本区域宽度。如何解决这个问题?

javascript - 长轮询 - Internet Explorer 8 的问题

javascript - AJAX 发布后追加 Div