日期:2014-05-16  浏览次数:20567 次

jquery给HTML元素添加 事件
一段html代码中  <button type="button">点击</button>
用js或jquey怎么变成  <button type="button"  onclick="But_Click('aa')">点击</button>


------解决方案--------------------
给按钮添加一个ID
 <button type="button" id=“bt1”>点击</button>

Js--JQ:
$("#bt1").attr("onclick",function(){
   alert("111");
})

大概这样
------解决方案--------------------
引用:
Quote: 引用:

给按钮添加一个ID
 <button type="button" id=“bt1”>点击</button>

Js--JQ:
$("#bt1").attr("onclick",function(){
   alert("111");
})

大概这样


用这个方法,为什么我追加 这段html代码段 的时候就 执行 alert,而追加后的 “点击” 按钮就不执行了


那可以看你是使用的jq哪个版本 具体的看文档吧
低版本可以用
$("#bt1").live("click",function(){

});

高版本用:
$("body").on("click","#bt1",function(){

});

------解决方案--------------------
引用:
Quote: 引用:

给按钮添加一个ID
 <button type="button" id=“bt1”>点击</button>

Js--JQ:
$("#bt1").attr("onclick",function(){
   alert("111");
})

大概这样


用这个方法,为什么我追加 这段html代码段 的时候就 执行 alert,而追加后的 “点击” 按钮就不执行了


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<script type="text/javascript" src="jquery-1.js">
</script>
<script type="text/javascript">
  var sa =  $("#bt1");
   function ale(){
     //alert(sa)
 document.getElementById('bt1').setAttribute('onclick','gogogo()')
 
   }
 function  gogogo(){
     alert("ou yeah");
 }
</script>
<body>
<input  type="button" id="bt1" value="123"/>
<input type="button" id="bt2"  value="123312" onclick="ale()" />
</body>
</html>

已测试 可以使用  记得导入JQ