Javascript 为什么innerHTML 返回“未定义”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29435612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:21:29  来源:igfitidea点击:

Why is innerHTML returning 'undefined'?

javascriptjquery

提问by Yeats

I'm trying to catch the "value" inside this div, which is editable:

我试图捕捉这个 div 中的“值”,它是可编辑的:

<div class="editable-div" contentEditable="true">Hey</div>

I figured I could do this simply via JavaScript:

我想我可以通过 JavaScript 简单地做到这一点:

var changedText = $('.editable-div').innerHtml

However, this variable will always return "undefined", which confuses me.

然而,这个变量总是会返回“undefined”,这让我很困惑。

Can someone enlighten me on how to reach this "value"?

有人可以启发我如何达到这个“价值”?

回答by Legendary

It is jQuery - you have to use:

它是 jQuery - 你必须使用:

$('.editable-div').html()

回答by josh

A jQuery wrapped object is actually not the raw DOM node, but essentially an array of raw DOM nodes that can be acted upon with jQuery specific methods, such as .html(). If you want to interact with the DOM node, you can retrieve it by either iterating through the list or getting the element of that list if you know which one it is:

jQuery 包装的对象实际上不是原始 DOM 节点,而是本质上可以使用 jQuery 特定方法(例如.html(). 如果您想与 DOM 节点交互,您可以通过遍历列表或获取该列表的元素(如果您知道它是哪个元素)来检索它:

$('div').each(function(index, element) {
  element.innerHTML // ...
}

$('div').get(0).innerHTML
$('div')[0].innerHTML

Note that while it is "kind of" like an array, in that you can get DOM nodes using the array syntax of $('div')[0], you can't treat it like an array in Javascript. In other words, you can'tdo this:

请注意,虽然它“有点”像数组,因为您可以使用 的数组语法获取 DOM 节点$('div')[0],但不能将其视为 Javascript 中的数组。换句话说,你不能这样做:

$('div').forEach(function(element) {
  element.innerHTML
}

回答by Code L?ver

innerHtmlis used with javascript selector and you are using jQuery. so replace innerHtmlwith .html()or .text()function.

innerHtml与 javascript 选择器一起使用,而您正在使用 jQuery。所以替换innerHtml.html().text()函数。

Use this:

用这个:

var changedText = $('.editable-div').html();

回答by Titi Wangsa bin Damhore

innerHtml is DOM. try $('.editable-div')[0].innerHtml

innerHtml 是 DOM。试试 $('.editable-div')[0].innerHtml