- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在使用 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/
Javascript 编程新手 我想从 textarea 获取文本并添加 html 段落标签,但我在 html 中遇到问题 [对象 HTMLParagraphElement] const textAr
当我尝试使用 javascript 写入 html 中的 id 时,我得到: [object HTMLParagraphElement]我正在使用innerhtml,但它仍然不起作用。我查看了不同的答
我在使用 jQuery 中的变量时遇到困难。var 需要返回窗口的宽度。为了测试这个,我写了一些代码,当我点击一个按钮时,宽度会显示在一个段落中: var update = function() {
我是 Javascript 初学者,我需要一些帮助。所以,我需要,当我按下按钮时,出现“左侧”段落 function myFunction() {
我是新手。这是我的代码: function replyOne () { document.getElementById("comment_content"
为什么以下代码显示 [object HTMLParagraphElement] 而不是元素内容?我也尝试添加 .innerHTML ,但这也只是显示未定义,这更加令人困惑。任何帮助将不胜感激。谢谢
我正在尝试让 Javascript 根据页面其他地方的内容(特别是购物车摘要中的项目名称)读取和编写段落。问题是我无法让 Javascript 正确编写它们。 我需要写的段落是“Order Inclu
我想清楚地了解BOM结构。 问题1:例如我有一个html文档,只有一个元素 伊西德 。当浏览器分析 html 文档时,它开始在 BOM 树内构建 DOM 树,并且我的段落元素被转换为 p放置在 DOM
我正在为我们网站上的搜索框构建自定义自动完成功能。 我编码了 keyup用于处理键盘输入的事件处理程序,用于滚动自动完成列表、输入选择元素/提交表单等... 我遇到的问题是我想要一个输入 keypre
我是一名优秀的程序员,十分优秀!