6

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

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

我使用 google chrome 控制台查看$("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;​ ">​…​&lt;/div>​
</div>​
]

我怎样才能得到 innerHTML :

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

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

非常感谢。

4

2 回答 2

6

要从有效的 jquery 选择器中获取普通的 javascript dom 对象,请使用get(0)or [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);
于 2012-11-23T19:16:42.150 回答
0

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

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

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

于 2012-11-23T19:10:22.707 回答