使用jQuery更改html onclick值

时间:2016-02-26 03:35:17

标签: jquery

我想找到并替换DOM中onCLick事件中的一段文本。我尝试了jQuery find contains,可能更多,但没有一个工作。你能帮忙吗?有多个onClick事件具有相同的“类”,所以我想首先查找Click OK to cancel this booking.然后用“他在这里新文本”替换它

这就是我所拥有的

`<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>

2 个答案:

答案 0 :(得分: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 :(得分:1)

&#13;
&#13;
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)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

&#13;
&#13;
$("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'))
});
&#13;
<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>
&#13;
&#13;
&#13;