当我构建页面时,我正在创建大量选择列表(下拉列表)。下拉列表基于外部数据文件,因此我在运行时设置 ID。由于
<% name="TypeA" + specialIDString %>
<select id="<%= name %>" >
blah
blah
</select>
我事先不知道 ID,因此如何添加事件侦听器?我可以在 DOM 中搜索 id 中包含“TypeA”的所有 id,然后为每个 id 添加一个侦听器吗?
我知道如何在 javascript 中触发 onLoad() 方法,在页面加载后,我只想知道如何搜索 DOM 以查找其中包含特定字符串的 ID。谢谢。
I am creating lots of select lists ( drop downs) when I build the page. The drop downs are based on external data files, so I set the id's at runtime. Something like
<% name="TypeA" + specialIDString %>
<select id="<%= name %>" >
blah
blah
</select>
How do I then add an event listener, since I don't know the ID ahead of time? Can I search the DOM for all id's with "TypeA" in the id, and just add a listener to each one of them?
I know how to trigger an onLoad() method in javascript, after the page is loaded, I just want to know how to search the DOM to find ID's with a particular string in them. Thanks.
发布评论
评论(5)
仅供记录,普通 JavaScript 答案:
然后:
现在您可以使用 for 循环将处理程序绑定到数组中的每个元素。
Just for the record, the vanilla JavaScript answer:
and then:
Now you can use for loop to bind handlers to each element from the array.
如果你使用 jQuery,你可以简单地这样做:
If you use jQuery you can do this simply like:
您可以内联添加事件侦听器并直接传递元素。
您可以做的另一件事是像这样传递事件属性:
然后在 myfunction 中, event.target 将是触发调用的元素。您可以通过
event.target.id
获取 id。You can add the event listener inline and directly pass the element.
Another thing you can do is pass the event attribute like this:
Then in myfunction, event.target will be the element that triggered the call. You could get the id with
event.target.id
.如果您无法具体知道 ID,您还可以采取其他措施。
一种选择是使用类名;另一种选择是在 ID 前面添加一些静态内容(用 jquery 的说法),您可以使用开头选择器。
它会起作用,但它不是最好的做事方式,特别是如果您有多个生成的元素。它也相对较慢。
按 CSS 类名称选择可能是最好的方法。
If you can't know the ID specifically there are other things you can do.
One choice is to use a class name; another option is to prepend the ID with something static and (in jquery parlance) your can use a starts-with selector.
It will work but its not the best way of doing things, especially if you'll have more than one generated element. It's also relatively slow.
Selecting by CSS Class name would probably be the best way.
如果你有 jQuery,那么使用 jQuery 查询选择器就很容易了。但如果没有:
向您的元素添加一个类:
使用
getElementsByClassName
访问您的元素循环元素并添加事件侦听器
我知道 getElementsByClass 名称在 IE6(或 7 中也不起作用?)。但这是我的解决方案。也许我可以用 x-browser 解决方案更新它
if you have jQuery its easy with jQuery query selector. but if not:
Add a class to your element:
Use
getElementsByClassName
to reach your elementsLoop around elements and add event listener
I know getElementsByClass name don't work in IE6 (or 7 also?). But this is my solution. Maybe I can update it with x-browser solution