Javascript blur-click 不能一起工作

标签 javascript html click onblur

我有 following code :

HTML:

<input type='text' class='a' />
<div class='inst' tag='a'></div>
<input type='text' class='b' />
<div class='inst' tag='b'></div>
<input type='text' class='c' />
<div class='inst' tag='c'></div>

JS:

$(function() {
    $('.inst').click(function() {
        alert($(this).attr('tag') + ' clicked');
    });

    $('[type=text]').focus(function() {
       show_inst($(this).attr('class'));
    }).blur(function() {
       //hide_inst($(this).attr('class'));
    });

    function show_inst(tag) {
        $('div.inst[tag=' + tag + ']').html(tag + ' instructions');
    }

    function hide_inst(tag) {
        $('div.inst[tag=' + tag + ']').html('');
    }
});

CSS:

.inst {
    width: 200px;
    height: 100px;
    border: 1px solid black;
    margin: 10px;
    cursor: pointer;
}

它工作正常:当 inst 被点击时,我看到警告消息,当输入成为焦点时,指令出现。

现在我希望不相关的指令在模糊时消失。所以我尝试在 blur() 中添加注释行。它不是那样工作的,因为 blur() 首先被调用并删除了指令,所以如果我点击指令 - 没有任何反应。

我该如何解决这个问题?

最佳答案

如果您的唯一问题是指令在发出点击之前被隐藏,请考虑添加一个微小的延迟。这基本上会导致您的隐藏指令在处理完点击后执行。

像这样:

$('[type=text]').focus(function() {
   show_inst($(this).attr('class'));
}).blur(function() {
   setTimeout(function(){
     hide_inst($(this).attr('class'));
   }, 50); // make this happen after any other events
});

关于Javascript blur-click 不能一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3385590/

相关文章:

javascript - 弹出掩码非常非常快地显示

javascript - 如何扩展 Button 组件并允许空间事件

javascript - 有没有办法取回在 Prototype 中使用 Event.observe 注册的匿名事件处理程序?

javascript - 我不明白如何使用 document.getElementById (‘id’ ).onclick

css - 单击时更改链接的 Css

javascript - 如何在 Isotope.js 的链接点击上触发事件?

javascript - 函数调用本身不起作用(无限循环,Javascript)

javascript - 可搜索下拉菜单

html - :out-of-range and :invalid?有什么区别

javascript - JQuery:组合点击/触发元素以更高效地编写代码?