一、问题
1.使用jquery获取元素的div,报错 $(...)[0].width不是一个函数。但是jquery确实有一个width方法用于获取元素的宽度。
2.代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>各种各样的宽度和高度呀</title>
<style>
.outer {
width: 500px;
height: 600px;
background-color: red;
padding: 20px;
border: 10px solid black;
margin: 30px;
}
.inner {
width: 200px;
height: 200px;
background: green;
padding: 20px;
border: 10px solid black;
margin: 30px;
}
</style>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body>
<div class="outer" id="outerdiv">
<div class="inner" id="innerdiv"></div>
</div>
</body>
<script>
window.onload = () => {
// 使用标签选择器时,默认取到第一个符合的标签中的属性和方法
//取到第一个div outer 500
console.log("div", $("div").width())
// $("div")[0]是一个 dom元素 ; $($("div")[0])是一个jquery对象
console.log("$('div')[0]是一个dom元素",$("div")[0])
console.log("outerdiv:","width:"+$("div")[0].width())
}
</script>
</html>
3.具体错误:
二、原因
1.打印后才发现, $(...)[0]竟然是一个 DOM对象!!!
1) DOM对象只能用offsetWidth、clientWidth、scrollWidth三个属性获取宽度, 没有width这个属性,更没有width方法
2) jQuery对象只能用width、innerWidth、outerWidth方法获取宽度
三、解决方法
1.在外面加一层$(),转换为jquery对象即可使用 width 方法
2.代码如下:
$($("div")[0]).width()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>各种各样的宽度和高度呀</title>
<style>
.outer {
width: 500px;
height: 600px;
background-color: red;
padding: 20px;
border: 10px solid black;
margin: 30px;
}
.inner {
width: 200px;
height: 200px;
background: green;
padding: 20px;
border: 10px solid black;
margin: 30px;
}
</style>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body>
<div class="outer" id="outerdiv">
<div class="inner" id="innerdiv"></div>
</div>
</body>
<script>
window.onload = () => {
// 使用标签选择器时,默认取到第一个符合的标签中的属性和方法
//取到第一个div outer 500
console.log("div", $("div").width())
// $("div")[0]是一个 dom元素 ; $($("div")[0])是一个jquery对象
console.log("$('div')[0]是一个dom元素",$("div")[0])
console.log("outerdiv:","width:"+$($("div")[0]).width())
}
</script>
</html>
2.运行结果:
四、总结
1.juqery对象才能使用方法获取宽高,如果报错:Uncaught TypeError: $(...)[0].width is not a function,请检查一下 调用方法的 $(...)[0]是不是juqery对象
2.dom对象只能使用属性获取宽高
/*
希望对你有帮助!
如有错误,欢迎指正,非常感谢!
*/