设置和删除onclick属性

时间:2017-09-13 13:23:03

标签: javascript jquery html

所以我试图从div“#link”中删除onclick属性。它不会删除。它也不适用于为onclick设置属性。似乎编辑onclick的任何东西似乎都没有影响它。我需要它来删除“onclick”的属性并将其设置为另一个属性。感谢

$(document).ready(function() {
  var attribute = $('#link').attr("onclick");
  var linklength = (attribute.split("'").length - 1);
  if (linklength > 5) {
    $('#link').removeAttr("onclick");
        $('#link')[0].setAttribute('onclick', 'test');
    console.log(attribute);
    console.log(linklength);

  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="link" onclick="skinPopup('UserDirectory','for name ','#userBio');">

</div>
<p id="title">Te'st</p>

1 个答案:

答案 0 :(得分:0)

不确定您要实现的目标,因为您已经使用了jQuery,因此可以简化操作。像这样的东西

&#13;
&#13;
$(document).ready(function() {
	var $link = $("#link");
	function skinPopup(directory, statement, id){
		console.log(directory, statement, id);
	}
	
	$link.on('click', function(){
		skinPopup('UserDirectory','for name ','#userBio');
	});
	
	//removing click event after 3s
	setTimeout(function(){
		$link.addClass('red');
		$link.off('click');
		// attaching mouseover and mouseout event
		$link.on('mouseover', function(){
			$(this).removeClass('red');
		}).on('mouseout', function(){
			$(this).addClass('red');
		})
	}, 3000)
 		
});
&#13;
.red{
	background: red;
}
&#13;
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
	
<div id="link">
Link
</div>
<p id="title">Te'st</p>	
	
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

</body>
</html>
&#13;
&#13;
&#13;

请注意,我可以根据您的要求添加条件,而不是在特定时间后删除click事件。 attributelinklength似乎都没有必要,这就是我删除它的原因。

了解有关事件监听器的更多信息

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener http://api.jquery.com/on/
http://api.jquery.com/off/

希望这有帮助,如果您有任何疑问,请与我联系。

相关问题