简体   繁体   English

在href标记中执行javascript代码

[英]Execute javascript code in a href tags

I have a page with several (100+) entries like this: 我有一个包含多个(100+)个条目的页面,如下所示:

<a href="javascript:removeFromCart(12302, 2);" class="remove">Remove</a>

Now I am looking for a jQuery snippet which can be run in the console and helps me to "click" all those "links" and execute the javascript function removeCart() with the respective parameters. 现在,我正在寻找可以在控制台中运行的jQuery代码段,并帮助我“单击”所有这些“链接”并使用相应的参数执行javascript函数removeCart()。

This does not work: 这不起作用:

$("a[href^='javascript']:contains('Remove')").click()

Any ideas? 有任何想法吗?

You can't use .click() here, because there is no event binding for the anchor. 您不能在此使用.click() ,因为锚点没有事件绑定。 You need to manually execute the contents of the href attribute, and that can easilly be done using eval() : 您需要手动执行href属性的内容,可以使用eval()轻松实现:

$('.remove').each(function() {
    eval(this.href);
});

You can add a new field and pass the parameters there like <a href="#" data-a="12302" data-b="2" class="remove">Remove</a> 您可以添加一个新字段,并在其中传递参数,例如<a href="#" data-a="12302" data-b="2" class="remove">Remove</a>

$("a.remove").each(function(){
    var param1 = $(this).data('a');
    var param2 = $(this).data('b');
    removeFromCart(param1, param2);
});

.trigger("click") does not actually perform a user click, but any code binding to the "click" event. .trigger("click")实际上并不执行用户单击,而是绑定到“ click”事件的任何代码。 You need to set the window location instead: 您需要设置窗口位置:

$("a[href^='javascript']:contains('Remove')").each(function() {
  window.location.href = $(this).prop("href");
});
 $('.remove').trigger('click',function(){
       // place your code
 });

You can move the parameters in the javascript function to data attributes first 您可以先将javascript函数中的参数移至数据属性

<a href="#" data-param1="20433" data-param1="2" class="remove">Remove</a>

then work on the class selector. 然后在类选择器上工作。

$("a.remove").each(function() {
  var param1 = $(this).attr('data-param1');
  var param2 = $(this).attr('data-param2');
  removeFromCart(param1, param2);
});

Well, the only way to trigger the code is actually to execute it. 好吧,触发代码的唯一方法实际上是执行它。

$("a[href^='javascript:removeFromCart']").each(function() {
    eval($(this).attr('href').substr(11));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM