昨天在做一个H5页面调查问卷的时候碰到了一个很奇葩的问题,给一个元素添加点击事件的时候在安卓上面可以实现添加元素,但是在IOS上面没有起作用。一开始我是使用的下面的第一种方法写的点击事件,但是并不可以在新添加的元素上面实现点击事件。所以我该用了绑定方法on来给添加元素按钮添加点击事件。是可以实现的。但是到了IOS上面失去了点击事件,又去度娘查了下才知道原因,因为IOS上面没有click点击事件,在IOS上面使用touch事件来实现点击事件的。所以这就简单多了。具体解决方法如下
1.$(".box").click(function(){
var index = $(this).parent('.qa_item_add_boxs').parent('.qa_item_aed_boxs').children().length;
$(this).parent('.qa_item_add_boxs').parent('.qa_item_aed_boxs').append(`
<div class="qa_item_add_boxs">
<div class="qa_item_add_nums">${index + 1}.</div>
<input class="qa_item_add_input" type="text" placeholder="商品名" />
<input class="qa_item_add_input" type="text" placeholder="对应企业名" />
<div class="qa_add_imgBox">
<img class="qa_item_add_img" id="eight_add" src="res/img/add.png"/>
</div>
</div>
`);
})
2.$(document).on('click','.qa_add_imgBox',function(){
var index = $(this).parent('.qa_item_add_boxs').parent('.qa_item_aed_boxs').children().length;
$(this).parent('.qa_item_add_boxs').parent('.qa_item_aed_boxs').append(`
<div class="qa_item_add_boxs">
<div class="qa_item_add_nums">${index + 1}.</div>
<input class="qa_item_add_input" type="text" placeholder="商品名" />
<input class="qa_item_add_input" type="text" placeholder="对应企业名" />
<div class="qa_add_imgBox">
<img class="qa_item_add_img" id="eight_add" src="res/img/add.png"/>
</div>
</div>
`);
})
解决IOS上面不能实现点击事件的方法
1.把点击元素改为button或者a链接 (这种方法暂未发现其它问题,但并不推荐使用)
2.添加touchstart事件document.body.addEventListener('touchstart', function() {}) (暂不推荐)
3.给点击元素添加属性cursor:pointer即可 (推荐使用,简单方便,无副作用)