父母的stopPropagation正在禁用孙子的功能

时间:2016-09-22 19:46:11

标签: javascript jquery html

我有一个模态,当打开时获取此jquery语句:

  $(".modal-inner").on("click", function(e) {
    e.stopPropagation();
  });

问题是,嵌套在这个模态体中,我有一个子元素,我使用Clipboard.js,因此用户可以复制文本。 HTML如下:

 <div class="modal-inner"> <!-- stopPropagation applied to parent -->
   <div class="modal-close" for="modal-1"></div>
     <h1>Let's Connect</h1>
     <i class="e"></i>
     <p>You can reach me at:</p>
     <p class="em">
       <input id="emailToCopy" value="this.email@gmail.com"/>
       <!-- This grandchild's functionality is now disabled -->
       <button class="clip-btn" id="thisClip"  data-clipboard-action="copy" data-clipboard-target="#emailToCopy" value="clipBtn">copy email</button>
     </p>
 </div>

如果用户点击内部,.modal-inner上的stopPropagation会阻止模态关闭。这反过来会禁用我的按钮,该按钮在单击时执行脚本。我需要这个按钮来绕过父元素的stopPropagation。

3 个答案:

答案 0 :(得分:2)

您可以检查按钮是否被点击,并有条件地停止传播

$(".modal-inner").on("click", function(e) {

   if ( $(e.target).closest('#thisClip').length > 0 ) { // this is the button
       e.stopPropagation();
   }

});

答案 1 :(得分:0)

这可能并不优雅,但我相信会奏效:

$(".modal-inner").on("click", function(e) {

    if (!$("button").is(":hover")) e.stopPropagation();

});

答案 2 :(得分:0)

您可以尝试测试事件目标ID和tagName:

&#13;
&#13;
$('.modal-inner').on("click", function(e) {
  //
  // you may also use:
  //  if ( $(e.target).is('#thisClip') ) {
  //
  
  if (e.target.id = 'thisClip' && e.target.tagName == 'BUTTON') {
    e.stopPropagation();
    console.log('You clicked the button: stop propagation');
  } else {
    console.log('You did not click the button');
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="modal-inner"> <!-- stopPropagation applied to parent -->
    <div class="modal-close" for="modal-1"></div>
    <h1>Let's Connect</h1>
    <i class="e"></i>
    <p>You can reach me at:</p>
    <p class="em">
        <input id="emailToCopy" value="this.email@gmail.com"/>
        <!-- This grandchild's functionality is now disabled -->
        <button class="clip-btn" id="thisClip"  data-clipboard-action="copy" data-clipboard-target="#emailToCopy" value="clipBtn">copy email</button>
    </p>
</div>
&#13;
&#13;
&#13;