关于JS嵌套点击事件的问题。

时间:2024-04-26 21:33:46
$().click()  是点击命令
$().click(function(){代码}) 是绑定click事件,并不会直接运行。所以在嵌套的时候就有可能出现重复绑定的问题。下面是使用jsonp跨站访问代码
    myChart.on('click', function (params) {
var totalCount = 0;
var objectGidName = new Object();
var listr = "";
var lastinstancecourt = "";
lastinstancecourt = params.value.toString().substring(2);
$.ajax({
type: "get",
url: "http://localhost:60360/Test/ReadCaseChinaList",
dataType: "jsonp",
jsonp: "jsonpcallback",//指定回调函数,这里名字可以为任意
data: "category=00301&lastInstanceCourt=" + lastinstancecourt + "&jsonpcallback=?",
success: function (json) {
$('.m-r ul li').remove();
if (json != "") {
var jsons = eval('(' + json + ')');
var obj = jsons.Data;
totalCount = obj.length;
for (var i = 0; i < obj.length; i++) {
objectGidName[obj[i].Gid] = obj[i].Title;
listr = "<li><a href=http://www.pkulaw.cn/case/pfnl_" + obj[i].Gid + ".html?match=Exact>" + obj[i].Title + "</a></li>";
$('.m-r ul').append(listr);
}
}
totalpart.innerText = params.name + "(" + totalCount +")";
}
});
$('.m-l li').on('click', function () {
var totalCount = 0;
var objectGidName = new Object();
var listr = "";
var categorynow = $(this).find('a').attr('cluster_code');
$.ajax({
type: "get",
url: "http://localhost:60360/Test/ReadCaseChinaList",
dataType: "jsonp",
jsonp: "jsonpcallback",//指定回调函数
data: "category=" + categorynow + "&lastInstanceCourt=" + lastinstancecourt + "&jsonpcallback=?",
success: function (json) {
$('.m-r ul li').remove();
if (json != "") {
var jsons = eval('(' + json + ')');
var obj = jsons.Data;
totalCount = obj.length;
for (var i = 0; i < obj.length; i++) {
objectGidName[obj[i].Gid] = obj[i].Title;
listr = "<li><a href=http://www.pkulaw.cn/case/pfnl_" + obj[i].Gid + ".html?match=Exact>" + obj[i].Title + "</a></li>";
$('.m-r ul').append(listr);
}
}
totalpart.innerText = params.name + "(" + totalCount + ")";
}
});
});
});
解决办法:
(1)使用unbind("click")先解除事件然后绑定新事件
   <script>
$(function(){
$("#test").click(function(){
$("#test").unbind('click').click(function(){
alert("内部click执行");
});
alert("外部click执行");
});
})
</script>

(2)使用die()在live()前将绑定的事件都解除掉

         <script>
$(function(){
$("#test").die().live("click",function(){
$("#test").die().live("click",function(){
alert("内部click执行");
});
alert("外部click执行");
});
})
</script>

--参考地址:http://www.phpddt.com/dhtml/jquery-click-problem.html