use*_*627 2 javascript jquery attributes element
我在javascript中创建一个元素,给它一个ID,然后通过jQuery访问它.我认为这很简单,但由于某种原因,这不起作用:
var img = document.createElement('img');
img.id = "uploadedimg";
if($('#uploadedimg').length==0)
alert("it's not there");
else
alert("it is there!");
Run Code Online (Sandbox Code Playgroud)
我得到的提醒是"它不存在".我知道如何在jQuery中创建一个元素,但我想知道这个代码有什么问题.
您必须在使用jQuery在DOM中查找之前附加元素.
使用该appendChild方法执行此操作.例如:
document.body.appendChild(img);
Run Code Online (Sandbox Code Playgroud)
然后,使用jQuery访问它.
另一种方法是直接将元素转换为jQuery对象,如下所示:$(img).之后,您可以使用jQuery的常用方法.
| 归档时间: |
|
| 查看次数: |
1168 次 |
| 最近记录: |