[英]How to dynamically change a parameter of a javascript call from the href attribute of an element
Is there a way to dynamically change what parameters are passed to a javascript function from an html element? 有没有办法动态更改从html元素传递给javascript函数的参数? For instance, say I have the following: 例如,说我有以下内容:
<a id="myElement" href="javascript:myFunction('myParam');">Click me!</a>
How can I change 'myParam' to another parameter, say 'myParam2'? 如何将'myParam'更改为另一个参数,比如'myParam2'? An answer using either javascript or jquery is fine with me. 使用javascript或jquery的答案对我来说很好。 For simplicity's sake, feel free to suppose I can find this element by document.getElementById('myElement') or some other means. 为简单起见,请随意假设我可以通过document.getElementById('myElement')或其他方法找到此元素。
What I would do instead is bind a click handler and use this
to figure out which was clicked. 我要做的是绑定一个单击处理程序并使用this
来确定单击了哪个。
$('#myElement').click(function () {
console.log($(this).text()); // Should dump "Click me!" to the console.
});
You could then add attributes to your links, such as data-someParam="my value"
and access them with .attr()
. 然后,您可以向链接添加属性,例如data-someParam="my value"
,并使用.attr()
访问它们。
To accomplish what you want you can do something like this 要完成你想要的,你可以做这样的事情
var ChangeParam = function(el,newParam) {
//make sure things aren't broken:
if(typeof el !== 'undefined' && el.href && typeof newParam !== 'undefined') {
var parta = el.href.split('(')[0] + '('; //get the stuff before the param
var partb = ')' + el.href.split(')')[1]; //get the stuff after the param
el.href = parta + '"' + newParam + '"' + partb; //put it all together
} else { return false; }
}
ChangeParam(document.getElementById('myElement'),'meow');
Edit: I made it a pretty function, hooray! 编辑:我做了一个漂亮的功能,万岁!
Should be able to use this as well: 也应该能够使用它:
document.getElementById('myElement').href = "javascript:myFunction('myParam2');"
Cheers, LC 干杯,LC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.