我是javascript的新手。
当用户输入任何文本或点击搜索图标时,我需要获取搜索文本值并将该值作为查询参数传递并将其重定向到搜索结果页面。
这里的问题是,当页面加载时,它直接重定向到搜索结果页面而不输入任何文本。你能不能让我知道我做错了什么?
http://localhost:3000/search/searchresults.html?query=&filter=newsroom&site=allsite_all&ei=r1_search
// Only run function if the newssearch search field exists
if ($('#search_banner-q_newsroom').length >= 1) {
$("#search_banner-q_newsroom").on('keypress', setupNewsroomSearch());
}
function setupNewsroomSearch() {
var tracking;
if ($(".self-service-search").length > 0) {
tracking = "&ei=r2_pt_search";
} else {
tracking = "&ei=r1_search";
}
redirectToSearchPage($("#search_banner-q_newsroom").val(), "newsroom", "site_all", tracking);
}
<form class="search_box_wrapper">
<div class="search-box">
<input type="text" id="search_banner-q_newsroom" aria-label="Search" name="query" placeholder="Search" />
<i class="icon-magnifying-glass search_desktop-newsroom-submit"></i>
</div>
</form>
答案 0 :(得分:1)
问题是因为您在加载时立即调用setupNewsroomSearch()
函数并将其返回值提供给keypress
处理程序。相反,您需要为事件处理程序提供函数的引用,如下所示:
$("#search_banner-q_newsroom").on('keypress', setupNewsroomSearch); // Note: () removed
另请注意,if
语句是多余的。 jQuery容忍在没有元素匹配的jQuery对象上调用函数。这是JS逻辑的整理版本:
$("#search_banner-q_newsroom").on('keypress', setupNewsroomSearch);
function setupNewsroomSearch() {
var tracking = $(".self-service-search").length > 0 ? '&ei=r2_pt_search' : '&ei=r1_search';
redirectToSearchPage($(this).val(), 'newsroom', 'site_all', tracking);
}