使用 jQuery 替换更改 onclick 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14365731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:30:48  来源:igfitidea点击:

Changing onclick attribute using replace with jQuery

jqueryattributesreplaceonclickattr

提问by Shad Gagnon

Do someone know what is the best way to replace some string inside a onclick attribute ?
I need to get the current valueand replace some text inside parameters.

有人知道在 onclick 属性中替换某些字符串的最佳方法是什么吗?
我需要获取当前值并替换参数中的一些文本。

Exemple,
I have this link:

例如,
我有这个链接:

<a href="#" onclick="myfunction('parameter1a','parameter1b')">My link</a>

And I want this:

我想要这个:

<a href="#" onclick="myfunction('parameter2a','parameter2b')">My link</a>

In other words, I want something like this:

换句话说,我想要这样的东西:

$('a').attr('onclick', $(this).attr('onclick').replace('1', '2'));

And I know I can do this, but I need something dynamic retreiving the values of current element:

我知道我可以做到这一点,但我需要一些动态检索当前元素的值:

$("a").attr('onClick', "myfunction('parameter2a','parameter2b')");

Finally it working when I made a simple demo: http://jsfiddle.net/GkWhh/4/

当我做了一个简单的演示时,它终于工作了:http: //jsfiddle.net/GkWhh/4/

Thank you for your solutions !

感谢您的解决方案!

回答by undefined

$('a[onclick]').attr('onclick', function(i, v){
   return v.replace(/1/g, '2');
});

http://jsfiddle.net/cj9j7/

http://jsfiddle.net/cj9j7/

If you need something more dynamic do not use onclickattributes, changing onclickattributes is hackish, you can use clickmethod instead.

如果你需要更动态的东西不要使用onclick属性,改变onclick属性是hackish,你可以使用click方法代替。

var param = 1;
$('a').click(function(){
   // ...

   if ('wildguess') {
     param = 1;
   } else {
     param++;
   }
})

回答by roman

sounds like a really bad idea but anyway - you can access the string value of the onlick attribute using something like that:

听起来是一个非常糟糕的主意,但无论如何 - 您可以使用类似的东西访问 onlick 属性的字符串值:

$('a').each(function() { this.attributes.onclick.nodeValue = this.attributes.onclick.nodeValue.replace('1', '2'); })

$('a').each(function() { this.attributes.onclick.nodeValue = this.attributes.onclick.nodeValue.replace('1', '2'); })

回答by Jai

You can do this: http://jsfiddle.net/SJP7k/

你可以这样做:http: //jsfiddle.net/SJP7k/

var atr = $('a').attr('onclick');
var str = atr.split('1');
var natr = str.join('2');
$('a').attr('onclick',natr);