【发布时间】:2017-03-25 16:03:36
【问题描述】:
执行搜索时我需要调用一个函数。搜索基于输入字段,不一定要集成到表单中。我只需要搜索字段的值。
由于我需要框架的一些功能——这是处理降价文件——我必须将绑定放在现有的$(document).ready(); 部分中。
我很难让它发挥作用。
用我的绑定记录准备好的部分
$(document).ready(function () {
// stage init stuff
registerFetchConfig();
registerBuildNavigation();
extractHashData();
appendDefaultFilenameToHash();
$(window).bind('hashchange', function () {
window.location.reload(false);
});
loadContent($.md.mainHref); // this parts generates the HTML for the page
// the part I integrated
console.log( ':: Before binding' );
$( '#srch-term' ).change( function( ) {
alert( "change" );
console.log( '### This is a binding on submit' );
} );
/*
$( '#subsearch' ).on( 'click', function( ) {
alert( "### This is binding on clicking the button" );
} );
*/
console.log( ':: After binding' );
// end of my part
});
同一html页面中的搜索字段
<form class="navbar-form" role="search" id="searchform" onsubmit="return false">
<div class="input-group">
<input class="form-control" placeholder="Search" name="srch-term" id="srch-term" type="text">
<div class="input-group-btn">
<button class="btn btn-default" type="submit" id="subsearch">
<i class="glyphicon glyphicon-search"></i>
</button>
</div>
</div>
</form>
文件本身可在线获取:mdwiki-debug.html 并基于 MDwiki
在萤火虫控制台我看到两个条目
:: Before binding
:: After binding
但是当我在搜索字段中输入一个字符串并按回车键或单击按钮时,控制台中没有显示任何内容。
我也尝试绑定提交,但这也不起作用。此外,表格不应最终提交,因为我必须避免重新加载。这就是为什么我在表单标签中有onsubmit="return false"。
当搜索字段已填满并且用户按回车键或单击按钮时,如何使绑定起作用?
【问题讨论】:
-
是搜索表单在你尝试绑定页面的时候做的吗?如果不是,委托事件处理程序可能是合适的。例如
$(document).on('click', '#subsearch', function(e) { ... }); -
我不确定,因为我现在不知道:什么时候搜索表单可用。 Ok 将尝试委托事件处理程序。
-
@Teemu
$(window).bind()被框架使用,他们使用的不是 jQuery 3.0,所以没关系。我在文档中也看到了这一点。 -
@Dymos 与代理配合得很好。如果你写一个答案,我可以接受。
标签: javascript jquery html binding