querySelectorAll和innerHTML逻辑

时间:2017-01-13 20:14:59

标签: javascript

在这种情况下,我无法构建JavaScript逻辑。为什么“Dollar”不会改为“Dolor”,而“dollar”改为“dolor”?但同时背景造型匹配。我的逻辑出了什么问题?谢谢。

var dollarEls = document.querySelectorAll("li .dollar");
        for (var i = 0; i < dollarEls.length; i++) {
                if(dollarEls[i] == "Dollar") {
                  dollarEls[i].innerHTML = "Dolor";
                }else if (dollarEls[i] == "dollar") {
                  dollarEls[i].innerHTML = "dolor";
                }else {
                  dollarEls[i].style.backgroundColor = "orange";
                }
        }
<ul>
    <li>Lorem ipsum <span class="dollar">Dollar</span> sit amet, consectetur adipiscing elit. Pellentesque mi tortor, convallis vitae rhoncus suscipit, finibus a dui. Quisque congue vulputate dolor vel facilisis. Nunc non ipsum porta, efficitur odio euismod, facilisis erat.</li>

    <li>Nam <span class="dollar">Dollar</span> ante, faucibus nec enim consequat, auctor faucibus nulla. Etiam bibendum commodo elit at euismod. Nullam elementum varius ligula sit amet accumsan. Nunc arcu nunc, mattis quis mollis eget, ultricies a nisi. Aliquam maximus luctus magna, vitae feugiat <span class="dollar">dollar</span> tempus non. Nulla dui ante, tempus at justo ut, ultricies cursus mauris.</li>
</ul>

2 个答案:

答案 0 :(得分:3)

您正在测试HTML元素对象的字符串表示是否等于字符串,而不是读取其文本内容(使用innerHTML)。

答案 1 :(得分:1)

而不是说

if(dollarEls[i] == "Dollar")

if(dollarsEls[i].innerHTML == "Dollar");

替换这两种情况

var dollarEls = document.querySelectorAll("li .dollar");
    for (var i = 0; i < dollarEls.length; i++) {
        if (dollarEls[i].innerHTML == "Dollar") {
            dollarEls[i].innerHTML = "Dolor";
        } else if (dollarEls[i].innerHTML == "dollar") {
            dollarEls[i].innerHTML = "dolor";
        } else {
            dollarEls[i].style.backgroundColor = "orange";
        }
}
<ul>
    <li>Lorem ipsum <span class="dollar">Dollar</span> sit amet, consectetur adipiscing elit. Pellentesque mi tortor, convallis vitae rhoncus suscipit, finibus a dui. Quisque congue vulputate dolor vel facilisis. Nunc non ipsum porta, efficitur odio euismod, facilisis erat.</li>

    <li>Nam <span class="dollar">Dollar</span> ante, faucibus nec enim consequat, auctor faucibus nulla. Etiam bibendum commodo elit at euismod. Nullam elementum varius ligula sit amet accumsan. Nunc arcu nunc, mattis quis mollis eget, ultricies a nisi. Aliquam maximus luctus magna, vitae feugiat <span class="dollar">dollar</span> tempus non. Nulla dui ante, tempus at justo ut, ultricies cursus mauris.</li>
    </ul>