直接上代码直观一点
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
</head>
<script src="jquery-1.10.1.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$(".li a").click(function(){
$(this).toggleClass("on");
});
});
/*******************************/
function ajax()
{
$('#ajax1').load("ajax.php");
}
/*******************************/
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ajax2").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax.php",true);
xmlhttp.send();
}
</script>
<style>
.on {font-size:20px; font-weight:bold; color:#03C;}
</style>
<div class="ul">
<div><input type="button" value="方法1" onclick="ajax()" /> <input type="button" value="方法2" onclick="loadXMLDoc()" /></div>
<div class="li"><a href="javascript:void(0)">点击变大</a></div>
<div id="ajax1"></div>
<div id="ajax2"></div>
</div>
<?php
$html = '<div class="li"><a href="javascript:void(0)">点击没反应</a></div>';
echo $html;
?>
有没有什么方法可以解决
改为on,要不执行
$(".li a").click(function(){
$(this).toggleClass("on");
});
这句只会给已经存在的dom对象添加事件,后续的加进来的因为上面的已经执行过是不会绑定上事件的
$(document).on('click','li a',function(){
$(this).toggleClass("on");
})
改成点击事件吧:
<a herf="javascript:;" onclick="方法('参数',this)">//注意this
function 方法('参数',obj)(){
$(obj).toggleClass("on");
}
添加事件的时候你ajax动态加载的dom并没有出来,所以你上面的$(".li a")并没有获取到动态加载的li上面。两种办法解决。
第一种是动态加载完成dom之后再添加事件。
第二种是使用jquery的事件委托,如果你的jq版本稍微高一点,on事件还有一个可选参数