jquery - How to dynamically change a parameter of a javascript call from the href attribute of an element - Stack Overflow

Is there a way to dynamically change what parameters are passed to a javascript function from an html e

Is there a way to dynamically change what parameters are passed to a javascript function from an html element? 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'? An answer using either javascript or jquery is fine with me. For simplicity's sake, feel free to suppose I can find this element by document.getElementById('myElement') or some other means.

Is there a way to dynamically change what parameters are passed to a javascript function from an html element? 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'? An answer using either javascript or jquery is fine with me. For simplicity's sake, feel free to suppose I can find this element by document.getElementById('myElement') or some other means.

Share Improve this question asked Jun 30, 2013 at 23:59 Tony WickhamTony Wickham 4,7664 gold badges31 silver badges35 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

What I would do instead is bind a click handler and use this to figure out which was clicked.

$('#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().

To acplish 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');

example: http://jsfiddle/q7R9B/2/


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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742362305a4429627.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信