getElementById - Javascript [英] getElementById - Javascript

查看:54
本文介绍了getElementById - Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Google自动填充JavaScript代码来完成地址。它跟踪获取Id document.getElementById('addressField')的输入字段。
我遇到的问题是输入字段的ID看起来像 myForm:j_idt329:addressField
我需要在许多不同的页面中使用它。因此,id每次看起来都不一样,但最后总是包含单词 addressField
是否有另一种方法来获取元素?也许用RegEx?
这里是完整的javascript:

  function initialize(){

var input =的document.getElementById( 'addressField');
var options = {
types:['geocode']
};

var autocomplete = new google.maps.places.Autocomplete(input,options);


google.maps.event.addDomListener(window,'load',initialize);

预先致谢。

解决方案

正则表达式不需要!您可以使用 querySelector

  document.querySelector([id * = 'addressField'])

如果我没有记错, * = 运算符在选择器中查找包含 addressField



的元素如果您试图获取一个包含多个这些元素的节点列表,只需使用 querySelectorAll 来代替。前者只返回列表的第一个节点, all 返回整个列表。



正如卢卡斯在评论: $ = 将匹配属性的末尾。两者都可以工作,但如果一方比另一方好,则不能100%确定。

I'm using the Google autocomplete javascript code for address completion. It tracks the imput field getting the Id document.getElementById('addressField'). The problem I have is that the id of the input field looks like myForm:j_idt329:addressField. I need this in many different pages. So the id looks each time different but always contains the word addressField at the end. Is there another approach how to get the element? Maybe with RegEx? Here is the complete javascript:

function initialize() {

var input = document.getElementById('addressField');
var options = {
    types: ['geocode']
};

var autocomplete = new google.maps.places.Autocomplete(input, options);

}
google.maps.event.addDomListener(window, 'load', initialize);

Thanks in advance.

解决方案

Regex not needed! You can use querySelector

document.querySelector("[id*='addressField']")

If I remember correctly, the *= operator in a selector looks for elements that contain addressField

If you are trying to get a nodelist of multiple of these elements, simply use querySelectorAll instead. The former just returns the first node of the list, all returns the whole list.

As Lucas said in the comments: $= will match the end of the attribute. Both will work, not 100% sure if one is better than the other however.

这篇关于getElementById - Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆