jquery 中的 $(“#”) 与 js中的document.getElementById(“”) 的区别

以前没注意过,认为jquery 中的 $("#") 与 document.getElementById("") 是一回事,指的是同一个东西。

这次项目开发在使用验证码生成的时候,发现两者不同,使用时需要注意!

通过以下测试:
js中代码

function reloadValidCode(o) { 

alert(o);

    o.src = "${pageContext.request.contextPath }/validCodeServlet?timed=" + new Date().getMilliseconds(); 

}

 

function refresh() { 

alert($("#imageYZ"));

   document.getElementById("imageYZ").src = "${pageContext.request.contextPath }/validCodeServlet?timed=" + new Date().getMilliseconds(); 

}

jsp中代码

<img src="${pageContext.request.contextPath }/validCodeServlet" id="imageYZ" alt="换一张" onclick="reloadValidCode(this)"/>

看不清?<a href="#this" onclick="refresh();"> 换一张</a>


我很打算在refresh()函数中使用
$("#imageYz").src =  "${pageContext.request.contextPath }/validCodeServlet?timed=" + new Date().getMilliseconds(); 
进行设置,但是发现不行;原来alert(o)的结果是:
[object HTMLCanvasElement]

而alert($("#imageYZ"))的结果是:

[objec Object]
从这里不难看出两者真的不一样;
再用firebug调试看一下,
$("#imageYZ")和document.getElementById("imageYZ")倒底是什么内容。调试结果如下:

$("#imageYZ")                         [img#imageYZ]
    
document.getElementById("imageYZ")    img#imageYZ

想必,看到这里,不用我说,大家也会想到结果了。

实际上,$("#imageYZ")[0]等同于 document.getElementById("imageYZ")
 
 
 
看你这里用的是jquery , $(id) 得到的是jquery 对象,是一个对dom 进行包装的对象,html() 是jquery 对象的方法。
document.getElementById("errorPsd") 是dom 对象,可以看作javascript 自带的对象。

$("#errorPsd").htm(); 等效于 document.getElementById("errorPsd").innerHTML

$("#errorPsd").html("更改span内容"); 等效于 document.getElementById("errorPsd").innerHTML="更改span内容“;
更多内容你可以参考jquery 帮助文档

猜你喜欢

转载自www.cnblogs.com/gongxianjin/p/11246466.html