我在使用 jQuery 中的变量时遇到困难。 var 需要返回窗口的宽度。 为了测试这个,我写了一些代码,当我点击一个按钮时,宽度会显示在一个段落中:
var update = function() {
width = $(window).width();
}
$(document).ready(
function() {
$('button').click(
function() {
update,
$('#width').text(width)
}
)
}
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="width">Width</p>
<button>test</button>
我得到“[object HTMLParagraphElement]”而不是宽度值。 我不明白为什么,因为当我运行这段代码时:
var width = $(window).width();
$(document).ready(
function () {
$('button').click(
function () {
$('#width').text(width)
}
)
}
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="width">Width</p>
<button>test</button>
我确实毫无问题地获得了值(value)。但是通过这种方式我无法在调整窗口大小后更新变量(我认为是因为该变量仅在页面加载时声明。)
这可能是一个真正的新手问题,但我非常渴望学习...
最佳答案
带有 ids
的“命名”元素被添加为 document
的属性。
这就是为什么当你之前调用 width
时,如果你没有这个元素,它应该是 undefined
<p id="width">Width</p>
因为你有这个元素,width
默认为 [object HTMLParagraphElement]
参见 Do DOM tree elements with ids become global variables?
此外,您需要使用 ()
调用 update
var update = function() {
return $(window).width();
}
$(document).ready(
function() {
$('button').click(
function() {
var width = update();
$('#width').text(width)
}
)
}
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="width">Width</p>
<button>test</button>
请注意,上面的代码返回一个值,而不是使用/分配一个全局变量width
。这是避免反模式的更好做法。
关于javascript - 变量返回 [object HTMLParagraphElement],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30557556/