【问题标题】:How JQuery handles with getElementsByClassName iteration?JQuery 如何处理 getElementsByClassName 迭代?
【发布时间】:2015-01-20 17:23:55
【问题描述】:

今天我正在缩短我的旧代码,我看到了这个代码:

$(".ceker").append("<a href='kit/");
$("#pdf").append("pdf");
$("#txt").append("txt");
$("#epub").append("epub");
$(".ceker").append("/7.");
$("#pdf").append("pdf");
$("#txt").append("txt");
$("#epub").append("epub");
$(".ceker").append("'><div class='menukitap'><div class='menuharry7 menuharresler'></div><h4>Ölüm Yadigarları İndir</h4></div></a>");

以前是这样输出的:

<a href="kit/pdf/7.pdf"><div class="menukitap"><div class="menuharry7 menuharresler"></div><h4>Ölüm Yadigarları İndir</h4></div></a>

我把它写得更短了:

function item()
{
    if( $('.ceker').attr('id') == 'pdf' )
    {
        return "pdf";
    }
    if( $('.ceker').attr('id') == 'txt' )
    {
        return "txt";
    }
    if( $('.ceker').attr('id') == 'epub' )
    {
        return "epub";
    }
}

$(".ceker").append("<a href='kit/" + item() + "/7." + item() + "'><div class='menukitap'><div class='menuharry7 menuharresler'></div><h4>Ölüm Yadigarları İndir</h4></div></a>");

这段代码也有效,但我不知道为什么会这样。在我看来,这段代码不应该工作,因为“ceker”类已经有3个不同的ID“pdf”“txt”和“epub”

所以这是我的问题:JQuery 如何处理getElementsByClassName Iteration(答案 1)? (我不明白这是怎么工作的if( $('.ceker').attr('id') == 'pdf' )

如果需要,这里是 HTML

<nav class="menu">
                    <span class="ara-menu-yer">Türkçe</span>
                    <a><li><section id="pdf" class="ceker"></section></li></a>
                    <a><li><section id="txt" class="ceker"></section></li></a>
                    <a><li><section id="epub" class="ceker"></section></li></a>
                    <span class="ara-menu-yer">English</span>
                    <a><li><section id="ingpdf" class="cekereng"></section></li></a>
                    <a><li><section id="ingdoc" class="cekereng"></section></li></a>
                </nav>

如果有拼写错误、语法错误或词汇错误,我深表歉意。我认为我无法解释我的问题,但我希望你能理解。

【问题讨论】:

  • .append() 将适用于集合中的所有元素,而使用 .attr() 获取属性将仅返回第一个匹配的元素特定属性。如果使用.attr() 作为 setter,.attr('anyattribute','anyvalue'),那么它将适用于 set 中的所有元素

标签: javascript jquery html attr getelementsbyclassname


【解决方案1】:

来自the docs

获取匹配元素集中第一个元素的属性值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 2011-04-12
    • 2011-06-03
    • 1970-01-01
    相关资源
    最近更新 更多