Through ajax, all the data is loaded in ul, and the ul li click event is added, but it cannot be triggered. If it is a ul event, it can be triggered.
ajax
/*省市*/
$("#proNum").click(function(){
$.ajax({type:"post",
url:"region/jsonRegion",
dataType:"json",
success:function(data){
$("#gj_disProvince").toggleClass("active");
var listr ="";
for(var i = 0; i < data.length; i++){
listr +="<li class='com-li gj_dispro' proNum='"+data[i].id+"'>"+data[i].placename+"</li>";
}
$("#assessPro").html(listr); //添加全部城市
}
});
});
Implementation diagram
Label
<p class="conselect mr-7" id="gj_disProvince">
<input class="inputype" readonly="readonly"placeholder="省份"
id="proNum" proNum="0">
<p class="p-r">
<p class="down-box">
<ul class="com-ul com-ul-288" id="assessPro">
</ul>
</p>
</p>
</p>
event
/*选择一个省 ,li[class='com-li gj_dispro'] 触发不了*/
$("ul[class='com-ul com-ul-288']").click(function(){
alert(1);
// 不明白为什么 ul 能触发,li就不行,
//请教一下如何获取到选择中li的省市和id
});
Because the ajax event is executed asynchronously, when you click, there is no li don structure
Save the id in the attr of li when looping
<li c_id="" >
Click event to get
var cid = $this.attr('c_id');
Use $parentNode.on('click',childNode,callback) to bind events. The principle is the event bubbling mechanism
Note three points:
1. The event registration function should be registered after the Ajax call is successful. You can call the event registration function in the ajax callback function.
2. Make sure your event registration function is not written incorrectly. Your event function here Wrong writing, directly assign a value to click, and then your class selector. I did not find any element whose class value is the value in your selector. If not, of course it cannot be selected.
3. Make sure the event has been registered before you click on the event.