您好我试图使用命名空间检测对元素的聚焦。这是我的工作代码:
(function($){
searchBox = {
element: $('div#block-search-form input[name=search_block_form]'),
focus: function(){
this.element.live('focusin',function(){
console.log('in');
});
this.element.live('focusout', function(){
console.log('out');
});
}
}
$(document).ready(function(){
searchBox.focus();
});
})(jQuery);
我的问题是如何在不使用.live()?
的情况下制作它修改
为了使它工作,我必须将一个元素作为一个函数,现在一切正常。当我没有它没有正确的背景时。 我的新代码:
(function($){
searchBox = {
element: function(){return $('div#block-search-form input[name=search_block_form]')},
init: function(){
this.focus();
},
focus: function(){
var that = this;
that.element().on({
'focusin': function(){
/*code*/
},
'focusout': function(){
/*code*/
}
});
}
}
$(document).ready(function(){
searchBox.init();
});
})(jQuery);
答案 0 :(得分:0)
使用
$(document).on("event", "element", function() {
而不是
this.element.live('focusin',function(){
请参阅以下代码示例:
(function($){
searchBox = {
element: $('div#block-search-form input[name=search_block_form]'),
focus: function(){
$(document).on("focusin", this.element, function () {
console.log('in');
});
$(document).on("focusout", this.element, function () {
console.log('out');
});
}
}
$(document).ready(function(){
searchBox.focus();
});
})(jQuery);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="block-search-form">
<input name="search_block_form" />
</div>
&#13;
答案 1 :(得分:0)
jQuery.live从1.7版本开始不推荐使用,并且已删除1.9 live方法。 您可以改为使用jQuery.on
(function($){
searchBox = {
element: $('div#block-search-form input[name="search_block_form"]'),
focus: function(){
this.element.on("focusin", function () {
console.log('in');
});
this.element.on("focusout", function () {
console.log('out');
});
}
}
$(document).ready(function(){
searchBox.focus();
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<div id="block-search-form">
<input name="search_block_form" />
</div>