簡體   English   中英

在querySelectorAll()中插入變量不起作用

[英]inserting a variable in a querySelectorAll() doesn't work

我做了一個for循環來為數組中的多個元素執行一些代碼。 在此for循環中有一個querySelectorAll(),但是由於querySelectorAll()在每個循環中都需要使用不同的元素,因此我嘗試在其中插入變量,但這給了我一個錯誤。 當我將那個變量的確切輸出直接輸入到querySelectorAll()中時,它確實起作用。 有誰知道如何解決這一問題?

(1)這是工作時的代碼,但是正如我所說,實際的className需要更改。 這就是為什么我要插入一個變量。

var tipSelectors0 = document.querySelectorAll(".tipContainer0 .pageContent-exercise-help-model-tip-select-container-li");

(2)這是無效的代碼。 但是正如您在注釋和控制台中看到的那樣。 變量輸出與我通過代碼(1)輸入的內容完全相同。

    Line637 var tipContainerClassName = "tipContainer" + j; //j = 0
    Line638 var newClassName ='".' + tipContainerClassName + ' .pageContent-exercise-help-model-tip-select-container-li"';
    Line639 console.log(newClassName); //Outputs:   ".tipContainer0 .pageContent-exercise-help-model-tip-select-container-li"
    Line640 var tipSelectors0 = document.querySelectorAll(newClassName);

(3)這是我在控制台中使用代碼(2)遇到的錯誤

".tipContainer0 .pageContent-exercise-help-model-tip-select-container-li" Leerstof.html:639
Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': '".tipContainer0 .pageContent-exercise-help-model-tip-select-container-li"' is not a valid selector. Leerstof.html:640

謝謝!

不需要在選擇器本身中使用引號。 您只需要刪除雙引號:

'.' + tipContainerClassName + ' .pageContent-exercise-help-model-tip-select-container-li'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM