我的 html 结构是这个样子的,设置了 input 的隐藏
扫描二维码1
比如我的代码是这个样子的
//父级元素为 tempBtn $(tempBtn).on('click',function(e){ //触发子元素的一个 input元素的 click $(this).find('[node-type=jsbridge]').click(); return false; });
如果这样子的话,会无限次的去触发子元素的事件,因为发生了冒泡,但是这种形式,怎么组织子元素事件的冒泡啊
试过这样子写也是不管用的
$(tempBtn).bind('click',function(e){ $(this).find('[node-type=jsbridge]').click(function(e){ return false; }); });
方案一:
改变html结构
<p class="qr-btn" node-type="qr-btn">扫描二维码1</p> <input node-type="jsbridge" type="file" name="myPhoto" value="扫描二维码1" />
再改下js
$(tempBtn).on('click',function(e){ //input[type=file] click 事件 $('input[node-type=jsbridge]').click(); });
方案二:
只改js
// 阻止 input click事件冒泡 $('[node-type=jsbridge]',tempBtn).on('click', function(e){ e.stopPropagation(); return false; }); $(tempBtn).on('click',function(e){ //触发子元素的一个 input元素的 click $(this).find('[node-type=jsbridge]').trigger('click'); });
方案三:
改变html结构,把p改成label;不需要js。
/* label的for属性对应input的id。可能在IE8等古老浏览器不起作用,需要把input{display:none} 改为input{height:0;overflow:hidden} */ <label class="qr-btn" node-type="qr-btn" for="input-file">扫描二维码1 <input id="input-file" node-type="jsbridge" type="file" name="myPhoto" value="扫描二维码1" /> </label>
为子元素添加click的处理事件,事件函数里加阻止冒泡的代码