简体   繁体   English

jQuery-删除模糊元素,但单击其子级

[英]jQuery - remove element on blur BUT catch click on his children

I have following code: 我有以下代码:

$('#myEl').blur(function(){
  $(this).remove('.children');
});

But the children element have links inside, with another jQuery actions which doesn't trigger because the .children is removed on blur, which I guess is triggered before the click action. 但是children元素内部有链接,另一个jQuery动作不会触发,因为.children会在模糊时被删除,我猜这是在click动作之前触发的。 Simple example: 简单的例子:

  1. Children is visible and #myEl have focus 儿童可见,#myEl专注
  2. I click on the children link 我点击孩子链接
  3. #myEl loses his focus #myEl失去焦点
  4. Children element is removed 子元素被删除
  5. Children link action is not triggered, because I guess link is not present anymore 儿童链接操作未触发,因为我猜链接不再存在

How to solve this? 如何解决呢? I was trying to delay remove: 我试图延迟删除:

$(this).delay(100).remove('.children');

With no luck. 没有运气。

If you are working with the delay way, you can't use jQuery .delay() since it only work on queued element (with animation). 如果您使用延迟方式,则不能使用jQuery .delay()因为它仅适用于排队的元素(带有动画)。

You can use setTimeout : 您可以使用setTimeout

$('#myEl').blur(function(){
  var $this = $(this);
  setTimeout(function(){
    $this.remove('.children');
  }, 100)
});

I've tried it with mousedown event and it worked fine. 我已经尝试过mousedown事件,并且效果很好。 I don't thing adding a delay is always a good option. 我认为增加延迟永远不是一个好选择。

   <input type="text" id="myEl"></input>
    <div class="children" >div child</div>
    <script>
        $('#myEl').blur(function(e){
            $('.children').remove();

        });

        $(".children").mousedown(function() {
            window.open('http://www.google.com')
        });
    </script>

And if you really want to add the click event for a specific reason then you can try this:- 如果您确实要出于特定原因添加click事件,则可以尝试以下操作:-

       $('#myEl').blur(function(e){
            if(mousedown){
               window.open('http://www.google.com'); 
               mousedown = false;
            }
            $('.children').remove();

        });
        $('.children').click(function(e){
            window.open('http://www.google.com')
        });
        $(".children").mousedown(function() {
           mousedown = true
        });

what about simply making the child elements hidden after a click? 只需在单击后隐藏子元素,该怎么办? Or maybe even having the child itself remove all children from its parent container after it has processed the click? 甚至在处理完点击之后,甚至让孩子自己从其父容器中删除所有孩子?

$('#myEl').blur(function(){ $(this).children('.children').hide(); }); $('.children').on("click",function(){ // perform your click-code actions here alert("I did it!"); // now remove your child elements from the parent $(this).parent().children('.children').remove(); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM