我已经复制了 JavaScript 谷歌地图,它工作得很好,但我需要获取 html 控件的类型并将其设置为 JavaScript。当我尝试从 lblTitle 获取值(value)时,它不起作用。
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Geocoding Demo 1</title>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript">
//var address = 'Warsaw, PL'; Original var
var address = document.getElementById('lblTitle').innerText;
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.TERRAIN,
zoom: 15
});
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
map.setCenter(results[0].geometry.location);
}
});
</script>
最佳答案
innerText 是检索文本内容的方法之一,与大多数方法一样,并非所有浏览器都支持它。如果我是正确的,Firefox 不支持 insideText,所以如果您在 Firefox 中进行测试,这可能就是您无法读取该值的原因。
你应该做的是使用JQuery的text()方法来获取值,因为它具有最大的跨浏览器支持,所以你不需要找出哪个浏览器使用哪个属性。所以在你的例子中:
var address = $("#lblTitle").text();
如果仍然没有给您文本,请在浏览器中检查 html,看看 id 是否实际上是 lblTitle。如果您有一个 Label 类型的服务器控件,其 ID 为 lblTitle,如下所示:
<asp:Label ID="lblTitle" runat="server" />
那么你的客户端id将不会是lblTitle,但会被加上前缀。客户端上的实际 ID 可以通过使用属性 ClientID 来请求。所以你的 javascript 行应该是:
var address = $("#<%= lblTitle.ClientID %>").text();
关于javascript - 如何从标签获取值并放入 document.getElementById ('label' ).innerHTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30963823/