简体   繁体   English

防止单击提前关闭数据集

[英]Prevent typeahead dataset from closing on click

I'm using the Typeahead library with a custom template in the results. 我在结果中使用带有自定义模板的Typeahead库。 The results contain a clickable link that should expand an element within the results. 结果包含一个可点击的链接,该链接应在结果中展开一个元素。 I am using jQuery.on to attach the click event handler to this element. 我正在使用jQuery.on将click事件处理程序附加到此元素。 When I click the element, the typeahead selected event is fired and the dataset box closes. 当我单击该元素时,将触发预输入的选定事件,并且数据集框将关闭。 I've tried adding e.stopPropagation() to the click event, but it doesn't appear to work. 我尝试将e.stopPropagation()添加到click事件中,但是它似乎无法正常工作。

The goal is to keep the typeahead tt-dataset search results box open when this link is clicked. 目的是在单击此链接时保持预输入tt数据集搜索结果框为打开状态。 Should I be doing this differently? 我应该这样做吗?

EDIT: I'm using bloodhound as the typeahead source 编辑:我正在使用猎犬作为预先输入源

$(document).on('click', '.mylink', function(e) {

    if ($(e.target).is('.mylink')) {
        //don't close the search results.  this isn't working
        e.stopPropagation();
        //show div
    }   

});

html template for the tt-dataset (I want the mylink anchor to keep the typeahead box open): tt数据集的html模板(我希望mylink锚点保持typeahead框处于打开状态):

<script id="search-template" type="text/x-handlebars-template">    
    <div>
        <strong>{{value}}</strong>
        <span><a href="javascript:;;" class="mylink">show</a></span>
        <div style="display:none">show this</div>
    </div>
</script>

According to JQuery API docs 根据JQuery API文档

Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events. 由于.live()方法一旦将事件传播到文档顶部便会对其进行处理,因此无法停止实时事件的传播。

So that explains your problem. 这样可以解释您的问题。

It is not elegant, but waiting for typeahead to create the suggestions in the DOM and THEN attaching an event handler on click works: 它不是很优雅,但是要等待在DOM中创建建议并在单击时在事件上附加事件处理程序,然后再等待:

http://jsbin.com/subupe/8/ http://jsbin.com/subupe/8/

Edit You might also use plain JavaScript with the onClick handler. 编辑您可能还会在onClick处理程序中使用纯JavaScript。 This should work regardless of the source of your autocomplete suggestions. 无论自动完成建议的来源如何,此方法都应起作用。

function dontClose(e) {
console.log('Dont close');
 e = e || event;
if (e.bubbles && e.stopPropagation) {
    e.stopPropagation();
}
else {   // all other browsers
    e.cancelBubble = true;
}

console.log($(e.target).text()); // do stuff with the target

return false;  

} }

/* ... */
templates : {
            suggestion: Handlebars.compile('<p><strong>{{value}}</strong></p><span><a href="javascript:;;" onClick="dontClose()" class="mylink">show</a></span><div style="display:none">show thisaa</div>')
      }

Updated jsbin: http://jsbin.com/subupe/9/ 更新的jsbin: http ://jsbin.com/subupe/9/

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

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