[英]I can't select an html element that was created dynamically with jquery
I have an html file 我有一个html文件
<body>
<div id="content">
</div>
</body>
Then I dynamically change the content with js 然后我用js动态更改内容
$.get("foo.html", function(data){
$("#content").html(data);
});
foo.html is an external html file that looks like this foo.html是一个看起来像这样的外部html文件
<span id="results">
</span>
This works to change the content of my page. 这可以更改我页面的内容。 I have checked in Chrome's dev tools, the page now looks like this
我已经检查了Chrome的开发工具,现在页面看起来像这样
<body>
<div id="content">
<span id="results">
</span>
</div>
</body>
Great. 大。 Now I want to display some results with jQuery
现在我想用jQuery显示一些结果
$("#results").text("some text");
This last part does not work. 最后一部分不起作用。 I can only assume it is because #results was created dynamically.
我只能假设是因为#results是动态创建的。 I know of this problem with event handlers and using
on
instead of click
but that is not the case here. 我知道事件处理程序和使用
on
而不是click
出现此问题,但事实并非如此。 I am simply trying to select the element. 我只是试图选择元素。
Of course my actual code is much more complicated and I have left some stuff out. 当然,我的实际代码要复杂得多,并且我遗漏了一些东西。 If you think there is something else that may be causing the problem please tell me and I will check.
如果您认为还有其他可能导致问题的原因,请告诉我,我会检查。
$.get is an asynchronous function, meaning it doesn't wait for completion before moving on. $ .get是一个异步函数,这意味着它在继续操作之前不会等待完成。 The way how jQuery gets around this is by using callback functions.
jQuery如何解决此问题的方法是使用回调函数。 Here, we have defined a callback function.
在这里,我们定义了一个回调函数。 We need to put the text modification inside the $.get callback.
我们需要将文本修改放入$ .get回调中。
<body>
<div id="content">
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$.get("foo.html", function(data){ //$.get callback function(data)
$("#content").html(data);
$("#results").text("some text");
});
</script>
</span
should be </span>
</span
应该是</span>
Make sure <span id="results">
exists on the page when you're acting on it. 对该页面进行操作时,请确保该页面上存在
<span id="results">
。 Because you are loading the content dynamically, there is a race condition, so act on it after it has loaded: 由于您是动态加载内容,因此存在竞争条件,因此请在加载后对其进行操作:
$.get(…).done(function(){ $('#results').text('foo') });
Beyond this, more information will need to be shown, perhaps a fiddle or code snippet. 除此之外,还需要显示更多信息,也许是小提琴或代码片段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.