对于Ajax返回的html,JQuery焦点无法通过新的1.7.1.on()方法工作
好的,我在这件事上有困难,所以非常感谢你的帮助 我有一个html输入字段: (id为:对于Ajax返回的html,JQuery焦点无法通过新的1.7.1.on()方法工作,jquery,Jquery,好的,我在这件事上有困难,所以非常感谢你的帮助 我有一个html输入字段: (id为:#数据输入),通过ajax调用返回 然后,在提交表单以便在#data_input字段中输入之前,我会检查表单是否正确 (注意:我在jquery的v1.7.1上) 如果未输入任何内容,我将更改字段的css,通过以下方式将其高亮显示为红色: $('#data_input').css('background-color','red') 这很好,所以我可以很好地瞄准它。但当用户通过以下方式进入字段时,我尝试撤消红色背
#数据输入
),通过ajax调用返回
然后,在提交表单以便在#data_input
字段中输入之前,我会检查表单是否正确
(注意:我在jquery的v1.7.1上)
如果未输入任何内容,我将更改字段的css,通过以下方式将其高亮显示为红色:
$('#data_input').css('background-color','red')
这很好,所以我可以很好地瞄准它。但当用户通过以下方式进入字段时,我尝试撤消红色背景时遇到了一个问题:
$('#data_input').on('focus', function(){$(this).css('background-color','white')});
但我什么都不知道,有什么想法吗
.live()
和.focus()
也不起作用:(
编辑:更新为在动态元素上使用.on 同样的情况也适用于我。。请参见此处,代码如下所示 HTML:
<div id="result" ></div>
$('#result').on ('focus', '#input_field', function () {
$(this).css ('background-color', 'white');
});
$('#result').on ( 'click', '#submit', function () {
if ($('#input_field').text() == '') {
$('#input_field').css ('background-color', 'red');
}
});
//added to dom after the binding. see above code.
$('#result').append('<input type="text" value="" id="input_field" />' +
'<input type="button" value="Submit" id="submit" />');
JS:
<div id="result" ></div>
$('#result').on ('focus', '#input_field', function () {
$(this).css ('background-color', 'white');
});
$('#result').on ( 'click', '#submit', function () {
if ($('#input_field').text() == '') {
$('#input_field').css ('background-color', 'red');
}
});
//added to dom after the binding. see above code.
$('#result').append('<input type="text" value="" id="input_field" />' +
'<input type="button" value="Submit" id="submit" />');
$('result')。在('focus','input#u field',函数(){
$(this.css('background-color','white');
});
$('result')。在('click','submit',函数(){
如果($('#输入_字段')。文本(){
$(“#输入_字段”).css('background-color','red');
}
});
//在绑定后添加到dom。参见上面的代码。
$('#result')。追加(''+
'');
试试这个:
$(document).on('focus', '#data_input', function(){$(this).css('background-color','white')});
您是说成功的
.css()
调用是在通过ajax加载字段之后进行的吗?如果您在ajax的成功回调中调用了.on()
,它应该可以工作。尝试在focus函数中使用console.log()
,而不是设置css,以确认函数是否被调用。请展示更多的代码,特别是你已经展示的代码行的上下文。很好的演示,但这与场景不同,因为你的输入从一开始就在页面中,而OP是通过ajax.Thx加载的@正如你所说的,使用.on有效。基本上,任何通过AJAX动态加载的DOM对象都需要通过未动态加载的父对象上的.on处理程序来检测。。。砰!每次都有效。