Javascript焦点不适用于动态加载的输入框 [英] Javascript focus does not work on dynamically loaded input box
问题描述
我在一个有输入元素的模板中有一个HTML标记。我通过Ajax调用并通过jQuery的 $(selector).html(response)
加载现有的html。
基本上它是一个从模板加载的弹出框。加载弹出框后,我想设置输入框的焦点。我写过这段代码:
$(#prescribe-input)。focus()
附加在现有HTML中,但它不起作用。我尝试以传统的JavaScript方式来执行此操作。 document.getElementById(prescribe-input)。focus()
两者都不起作用。出于测试目的,我尝试在应用程序的Index.html中创建示例输入框并设置焦点。它完美地工作。问题是,当我使用 $()。html()
加载html模板时,它无效。
任何方式来适当地集中它?
我知道这里的代码非常少,但问题是我相信自我解释。
jquery
,那么您可以在动态生成的元素上使用 .on()
$(#prescribe-input)。on(focus,function(){
//做任何你想要的
});
I have a HTML markup in a template which has input element. I load it via Ajax call and put in existing html using jQuery's $(selector).html(response)
.
Basically it is a pop up box which loads from template. After loading pop up box I want to set focus on input box. I've written this code :
$("#prescribe-input").focus()
after content is appended in existing HTML but it does not work. I tried doing it in traditional javascript way too document.getElementById("prescribe-input").focus()
Both do not work. For testing purpose I tried creating sample input box in Index.html of an app and set focus. it works perfectly. The problem is when I load html from template using $().html()
it does not work.
Any way to focus it properly?
I know the code is very less here but the question is self explanatory I believe.
if you are using jquery
then you can use .on()
on dynamically generated elements
$("#prescribe-input").on( "focus", function() {
//do what ever you want
});
这篇关于Javascript焦点不适用于动态加载的输入框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!