2016-02-26 73 views
2

我想查找並替換DOM中的onCLick事件中的一段文本。我試過jQuery findcontains可能會更多,但沒有人工作。你能幫忙嗎?有使用相同的「類」多的onclick事件,所以我想先來說一下Click OK to cancel this booking.,然後用`替換他新的一段文字在這裏」中使用jQuery更改html onclick值

這是我

`<a href="#" class="replaced_btn" onclick="return confirm('Click OK to cancel this booking.');"></a>` 

我希望它改變了這個 <a href="#" class="replaced_btn" onclick="return confirm('The New Piece Of Text Here');"></a>

+0

你就不能更改HTML? –

+0

不可以。這是從另一個js文件動態生成的 – nasty

+0

http://stackoverflow.com/questions/14365731/changing-onclick-attribute-using-replace-with-jquery –

回答

1

可以使用attribute contains filter

jQuery('.replaced_btn[onclick*="Click OK to cancel this booking."]').attr('onclick', function(i, value) { 
 
    return value.replace('Click OK to cancel this booking.', 'The New Piece Of Text Here') 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a href="#" class="replaced_btn" onclick="return confirm('Click OK to cancel this booking.');">test</a>

attribute equals

jQuery('.replaced_btn[onclick="return confirm(\'Click OK to cancel this booking.\');"]').attr('onclick', function(i, value) { 
 
    return value.replace('Click OK to cancel this booking.', 'The New Piece Of Text Here') 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a href="#" class="replaced_btn" onclick="return confirm('Click OK to cancel this booking.');">test</a>

1

var elem = '<a href="#" class="replaced_btn" onclick="return confirm(' + 'Click OK to cancel this booking.' + ');"></a>'; 
 
elem = elem.replace("Click OK to cancel this booking.", "The New Piece Of Text Here"); 
 
alert(elem)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

OR

$("a").click(function() { 
 
    var elem = $(this).attr('onclick'); 
 
    elem = elem.replace("Click OK to cancel this booking.", "The New Piece Of Text Here"); 
 
    $(this).attr('onclick',elem); 
 
    alert($(this).attr('onclick')) 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a href="#" class="replaced_btn" onclick="return confirm(' + 'Click OK to cancel this booking.' + ');"> Test </a>