Do autocomple. Need in the dropdown prompts to make links.
I use this plugin .
$(function () {
$('input[name="oem"]').autoComplete({
minChars: 4,
source: function (term, response) {
term = term.toLowerCase();
$.getJSON('/search.json?oem=' + term, function (data) {
var matches = [];
for (i = 0; i < data.length; i++)
if (~data[i].toLowerCase().indexOf(term))
matches.push(data[i]);
response(matches.slice(0, 11));
});
},
renderItem: function (item, search) {
search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g);
var re = new RegExp("(" + search.split(' ').join('|') + ")");
return '<div class="autocomplete-suggestion" data-val="' + item + '"><a href="#" onclick="javascript:document.location.href="#"">' + item.replace(re, "<b>$1</b>") + '</a></div>';
}
});
});
How to attach on to the onclick
event of the link?
Are there other variants?
You can put class on your dynamically generated <a></a>
tags inside renderItem
function, for example class="dynamically-added"
and then attach event handler to document that is listening for clicked item of this class. Check this demo:
$(document).ready(function(){ // This is how you can handle click event of dynamically added elements via jQuery $(document).on('click', '.dynamically-added', function(){ console.log('clicked -> ' + $(this).text()); }); var container = $('#container'); for(var i=1; i < 6; i++){ container.append('<a href="#" class="dynamically-added">Dynamically added '+i+'</a><br/>'); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> </div>
EDIT
So your code will look like this:
$(document).ready(function () {
// This is the event handler code
$(document).on('click', '.dynamically-added', function () {
console.log('clicked -> ' + $(this).text());
});
$('input[name="oem"]').autoComplete({
minChars: 4,
source: function (term, response) {
term = term.toLowerCase();
$.getJSON('/search.json?oem=' + term, function (data) {
var matches = [];
for (i = 0; i < data.length; i++)
if (~data[i].toLowerCase().indexOf(term))
matches.push(data[i]);
response(matches.slice(0, 11));
});
},
renderItem: function (item, search) {
search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g);
var re = new RegExp("(" + search.split(' ').join('|') + ")");
// Here check your <a> I added class="dynamically-added"
return '<div class="autocomplete-suggestion" data-val="' + item + '"><a href="#" class="dynamically-added">' + item.replace(re, "<b>$1</b>") + '</a></div>';
}
});
});
下面,我更改了在代码中构建返回字符串的方式,
return "<div class='autocomplete-suggestion' data-val='" + item + "'><a href='#' onclick='javascript:document.location.href="+\\""+"#"+\\""+">" + item.replace(re, "<b>$1</b>") + "</a></div>";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.