繁体   English   中英

无法从jQuery对象获取innerHTML

[英]Can not get innerHTML from a jQuery Object

我正在使用谷歌地图api。 我写了下面的代码。

<div id="map"></div>

我使用谷歌浏览器控制台查看$("div#map")

console.log($("div#map"));

结果是:

[
<div id=​"map" style=​"width:​ 1218.222222328186px;​ position:​ relative;​ background-color:​ rgb(229, 227, 223)​;​ overflow:​ hidden;​ -webkit-transform:​ translateZ(0)​;​ ">​
<div style=​"position:​ absolute;​ left:​ 0px;​ top:​ 0px;​ overflow:​ hidden;​ width:​ 100%;​ height:​ 100%;​ z-index:​ 0;​ ">​…​</div>​
</div>​
]

我怎样才能得到innerHTML:

<div style=​"position:​ absolute;​ left:​ 0px;​ top:​ 0px;​ overflow:​ hidden;​ width:​ 100%;​ height:​ 100%;​ z-index:​ 0;​ ">​…​</div>​

我试过$("div#map > div") ,但没有回复。 为什么? 是因为Javascript生成的innerHTML? 我怎样才能得到它并在上面的div中插入另一个div?

非常感谢你。

要从有效的jquery选择器获取普通的javascript dom对象,请使用get(0)[0]

$("#map")[0]//note that as id's are unique, you do not need to have anything else
            //in here to target them

一旦拥有了普通的DOM对象,就可以使用innerHTML

$("#map")[0].innerHTML

虽然更简单的方法,因为你已经在使用jQuery,将使用jQuery的innerHTML html版本。

$("#map").html()

至于你的第二个问题,你可以像这样在div中插入一个div:

var newDiv = document.createElement("div");
newDiv.innerHTML = "simple text, probably want to make more elements and set attributes and build them using .appendChild().";
$("#map")[0].appendChild(newDiv);

或者像地图的父级一样:

$("#map")[0].parentNode.appendChild(newDiv);

使用html()方法从jQuery对象获取html。

console.log($("div#map").html());

http://api.jquery.com/html/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM