如何使用jquery向超链接添加内联onclick事件?

时间:2011-12-21 15:08:56

标签: jquery

我需要使用jQuery生成近80个超链接。我做到了,一切都很好。现在我的客户要我在超链接上添加点击事件?我怎么能这样做?

我目前的链接是:

<a href="#" class="removed purchase-btn">Long Sleeve Breton Top</a>

但我需要补充一下:

$('<a onclick="site.exec('page', 'openInternal', {'url': 'http://www.site.in/en-GB/Products/quickshop.aspx?qsi=AM154YEL&amp;});"  href="#">link'+i+'</a>').appendTo('#hello');
  }

为此,我使用了这个功能,但没有用:

$(function (){

  for(i=0;i<80;i++){
    $('<a onclick="site.exec('page', 'openInternal', {'url': 'http://www.site.in/en-GB/Products/quickshop.aspx?qsi=AM154YEL&amp;});"  href="#">link'+i+'</a>').appendTo('#hello');
  }

})

但它不起作用。有什么想法使这项工作?

此链接我需要生成并输入应用程序。所以直接来自jquery的click事件我无法使用。严格来说,我需要将此代码放在内联..

3 个答案:

答案 0 :(得分:0)

使用事件处理程序而不是内联代码

$(function (){
  var parent = $("#hello");  //Get the element that will hold all the links.

  for(var i=0;i<80;i++){
      parent.append("<a href='http://www.site.in/en-GB/Products/quickshop.aspx?qsi=AM154YEL&amp;'>link"+i+"</a>");
      //Append a link with the URL in its href attribute
   }

    parent.on("click", "a", function(e) { //Select links under the #hello element and provide a click handler
        site.exec('page', 'openInternal', {
            'url': this.href //Use the href property of the link
        });
        e.preventDefault(); //Don't follow the href link
    });
}

答案 1 :(得分:0)

也许这会有所帮助:

$("a.removed").live("click", function(){
    //do something
});

答案 2 :(得分:0)

如果你的超链接包含在另一个div中,那么:

$("#divid a").each().click(function(){

    ......

});

$("a").each().click(function(){

    ......

});

根据您的要求进一步改进可以解决您的问题。

编辑:用引号包装选择器