简体   繁体   English

使jQuery内的<a>自动完成可点击

[英]Make <a> inside jQuery autocomplete clickable

I managed to add a link to the right of the jQuery autocomplete items, using the following code: 我设法使用以下代码添加jQuery自动完成项右侧的链接:

function onClientSelect(event, ui) {
    // My handling code goes here
    event.preventDefault();
}

$("#mypage input[name='client']").autocomplete({
    minLength: 1,
    appendTo: $(this).parent(),
    source: '/filter_client/',
    select: onClientSelect,
    focus: function (event, ui) {
        event.preventDefault();
    },
}).data("ui-autocomplete")._renderItem = function (ul, item) {
    return $("<li></li>")
        .data("item.autocomplete", item)
        .append("<a>" + item.label + "</a>")
        .appendTo(ul);
};

My server returns element label in this format: 我的服务器以这种格式返回元素标签:

<div class="ac-item-lb">My Item Label</div>
<a class="ac-item-a" href="/url_to_go_to/" target="_blank">View Detail</a>

What I want to do is to open the link in a new tab when I click on 'View Detail', which clicking any other area executes onClientSelect just like normal. 我想要做的是当我点击“查看详细信息”时打开新选项卡中的链接,单击任何其他区域就像正常一样执行onClientSelect。 However, currently left-clicking on the link also executes onClientSelect . 但是,当前左键单击链接也会执行onClientSelect The only way to open the link is to click the middle wheel or right mouse button and select 'open in new tab'. 打开链接的唯一方法是单击中间滚轮或鼠标右键,然后选择“在新选项卡中打开”。

I tried attaching a click event handler on the link with event.stopImmediatePropagation() but that doesn't seem to work. 我尝试使用event.stopImmediatePropagation()在链接上附加一个click事件处理程序,但这似乎不起作用。 Does anyone have any idea how to fix this? 有谁知道如何解决这个问题?

One way to do it is by defining a custom select function and by not using an <a> for the links 一种方法是定义一个自定义select函数,而不是使用<a>作为链接

HTML: HTML:

<div class="ui-widget">
    <label for="tags">Tags:</label>
    <input id="tags">
</div>

JS: JS:

 var availableTags = [
    "ActionScript",
    "AppleScript",
    "Asp",
    "BASIC",
    "C",
    "C++",
    "Clojure",
    "COBOL",
    "ColdFusion",
    "Erlang",
    "Fortran",
    "Groovy",
    "Haskell",
    "Java",
    "JavaScript",
    "Lisp",
    "Perl",
    "PHP",
    "Python",
    "Ruby",
    "Scala",
    "Scheme"];

$("#tags").autocomplete({
    source: availableTags,
    select: function (event, ui) {
        var elem = $(event.originalEvent.toElement);
        if (elem.hasClass('ac-item-a')) {
            var url = elem.attr('data-url');
            event.preventDefault();
            window.open(url, '_blank ');
        }
    }
}).data("ui-autocomplete")._renderItem = function (ul, item) {
    return $("<li></li>")
        .data("item.autocomplete", item)
        .append('<a>' + item.label + '<span class="ac-item-a" data-url="http://www.nba.com"> View Details</span></a>')
        .appendTo(ul);
};

JSFIDDLE . JSFIDDLE

Have you thought about putting a conditional in your click handler to not preventDefault when it is that link? 你有没有想过在你的点击处理程序中添加一个条件,以防止在链接时出现 preventDefault If you test if the element should function as normal then you can return early before the preventDefault and then the link should function as normal. 如果您测试元素是否应该正常运行,那么您可以在preventDefault之前提前return ,然后链接应该正常运行。

Here is an example ( JSBin ): 这是一个例子( JSBin ):

 function clickHandler(e) { // If the target element has the class `test-clickable` then the // function will return early, before `preventDefault`. if (this.className.indexOf('test-clickable') !== -1) { return; } alert('That link is not clickable because of `preventDefault`'); e.preventDefault(); } $('a').click(clickHandler); 
 a { display: block; } a:after { content: ' [class=' attr(class)']'; } 
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Title</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> </head> <body> <a class='test-clickable' href='http://www.google.com' target='_blank'>Link</a> <a class='test-not-clickable' href='http://www.google.com' target='_blank'>Link</a> </body> </html> 

Amir, regarding to your answer, I think that opening window inside javascript function from select event can be blocked by PopupBlocker Amir,关于你的回答,我认为popupBlocker可以阻止来自select事件的javascript函数内的打开窗口

pinghsien422 , your server side should return Json and not complete html , if you must return complete html, make the following changes: pinghsien422,您的服务器端应该返回Json并且不能完成html,如果必须返回完整的html,请进行以下更改:

1.Remove the clientSelect function 1.删​​除clientSelect功能

2.No 'a' tag is needed in renderData function 2. renderData函数中不需要'a'标记

 $("#mypage input[name='client']").autocomplete({
   minLength: 1,
  appendTo: $(this).parent(),
   source: '/filter_client/',
  focus: function (event, ui) {
    event.preventDefault();
  },
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
    .data("item.autocomplete", item)
    .append( item.label )
    .appendTo(ul);
};

Okay, jquery's event takes precedence over your select event - no matter what you do, you can't stop anything there. 好的,jquery的事件优先于你的选择事件 - 无论你做什么,你都无法阻止任何事情。 But you can proxify menuselect event and then decide if it should be invoked ( jsfiddle ). 但你可以代理menuselect事件,然后决定是否应该调用它( jsfiddle )。

var ac = $("#mypage input[name='client']").autocomplete({
    minLength: 1,
    appendTo: document.body,
    source: availableTags,
    focus: function (event, ui) {
        event.preventDefault();
    },
}).data("ui-autocomplete");
ac._renderItem = function (ul, item) {
    return $("<li></li>")
        .data("item.autocomplete", item)
    .append("<div>"+item.label+"<a class='link' href='http://test'>(http://test)</a></div>")
        .appendTo(ul);
};
var ms = $._data(ac.menu.element.get(0), 'events').menuselect[0].handler;
ac.menu.element.off("menuselect");
ac.menu.element.on("menuselect", function (ev) {
    if($(ev.originalEvent.target).hasClass("link"))
        return;
    ms.apply(this,arguments);
});

Try to do even.stopImmediatePropagation in onclick binding to link. 尝试在onclick绑定中进行even.stopImmediatePropagation链接。 Page is opening and select handler not executed. 页面正在打开并选择未执行的处理程序。

var li = $("<li></li>")
    .data("item.autocomplete", item)
    .append('<a class="ac-item-a" href="http://www.nba.com">' + item.label + '</a>')
    .appendTo(ul);

li.find('a').bind('click', function(event){ event.stopImmediatePropagation() });

return li;

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

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