父级元素触发子元素的 click 事件,事件执行完以后怎么组织子元素事件冒泡

我的 html 结构是这个样子的,设置了 input 的隐藏

<div class="qr-btn" node-type="qr-btn">扫描二维码1
            <input node-type="jsbridge" type="file" name="myPhoto" value="扫描二维码1" />
        </div>

比如我的代码是这个样子的

//父级元素为 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;
                });
            });
阅读 7.5k
2 个回答

为子元素添加click的处理事件,事件函数里加阻止冒泡的代码

方案一:

改变html结构

<div class="qr-btn" node-type="qr-btn">扫描二维码1</div>
<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结构,把div改成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>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题