Changing onclick attribute using replace with jQuery

前端 未结 3 1832
终归单人心
终归单人心 2020-12-18 11:15

Do someone know what is the best way to replace some string inside a onclick attribute ?
I need to get the current value and replace some text inside pa

相关标签:
3条回答
  • 2020-12-18 11:47

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

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

    0 讨论(0)
  • 2020-12-18 12:02

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

    var atr = $('a').attr('onclick');
    var str = atr.split('1');
    var natr = str.join('2');
    $('a').attr('onclick',natr);
    
    0 讨论(0)
  • 2020-12-18 12:04
    $('a[onclick]').attr('onclick', function(i, v){
       return v.replace(/1/g, '2');
    });
    

    http://jsfiddle.net/cj9j7/

    If you need something more dynamic do not use onclick attributes, changing onclick attributes is hackish, you can use click method instead.

    var param = 1;
    $('a').click(function(){
       // ...
    
       if ('wildguess') {
         param = 1;
       } else {
         param++;
       }
    })
    
    0 讨论(0)
提交回复
热议问题