Javascript JS Prototype 按类获取元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5250722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:21:44  来源:igfitidea点击:

JS Prototype get element by class?

javascriptprototypejs

提问by FLX

I got the following code and I'm trying to make it match on a class instead of on an id:

我得到了以下代码,我试图让它在一个类上而不是一个 id 上匹配:

Html:

网址:

<div id='testdiv'>
    <div class="lol">
        [First Title|<a class="external" href="http://test.com">http://test.com</a>]
        Another line
        [Second Title|<a class="external" href="http://test.com">http://test.com</a>]
        More text
        [Third Title|<a class="external" href="http://test.com">http://test.com</a>]
    </div>
</div>

Javascript:

Javascript:

var textContainer = document.getElementById("testdiv");
var linkText = textContainer.innerHTML;
var pattern = /\[([^|]+)\|([^>]+.?)[^<]*(<\/a>)\]/g;
var result = linkText.replace(pattern, "");

textContainer.innerHTML = result;

Full example: http://jsfiddle.net/JFC72/17/

完整示例:http: //jsfiddle.net/JFC72/17/

How can I make it match on "myclass" instead? Thanks!

我怎样才能让它与“myclass”相匹配?谢谢!

回答by bwest

Use a css selectorin prototype.

在原型中使用css 选择器

var textContainer = $$('div.myclass')[0];

jsfiddle

提琴手

回答by jon_darkstar

I think you need the $$method. It selects DOM elements that match a CSS selector strict. In this case you want

我想你需要这个$$方法。它选择与 CSS 选择器严格匹配的 DOM 元素。在这种情况下,你想要

var elements = $$('.myclass');

It returns a list of all matching elements in document order. You can access them by index or operating on all of them with things like each

它以文档顺序返回所有匹配元素的列表。您可以通过索引访问它们或使用诸如each

http://www.prototypejs.org/api/utility

http://www.prototypejs.org/api/utility

This is what Prototype is about. getElementById is oooold

这就是 Prototype 的意义所在。getElementById 是 oooold

回答by crmpicco

Here is a working example of how you would use eachin Prototype to loop through all elements with a class of order-cc-charged.

这是一个工作示例,说明如何each在 Prototype 中使用order-cc-charged.

var order_cc_charged = 0;

$$('order-cc-charged').each(function (elem) {
   order_cc_charged += parseFloat($('order-cc-charged').innerHTML);
});