简体   繁体   中英

JavaScript: How can i set a variable in a string

I would like to set attributes on all elements that id starts with "id-" followed by a number [eg id="id-0", id="id-1) and so on]. I thought about something like this:

<script type="text/javascript" >

function Prepare() {
    var = 0
    while(document.getElementById("id-{var}")) {
        document.getElementById("id-{var}").setAttribute("rows", "60");
        var += 1
    }

</script>

How can i set a var like this in JavaScript?

this should accomplish the task:

<script type="text/javascript" >

function Prepare() {
    var ct = 0
    while(document.getElementById("id-"+ct)) {
        document.getElementById("id-"+ct).setAttribute("rows", "60");
        ct += 1
    }

</script>

alternatively:

<script type="text/javascript" >
function Prepare() {
    for(var ct = 0;document.getElementById("id-"+ct);ct++) {
       document.getElementById("id-"+ct).setAttribute("rows", "60");
     }
</script>

Depending on compatability you could use querySelectorAll() :

function Prepare(){
    var els = document.querySelectorAll("[id^=id]");

    for(var i=0; i<els.length; i++){
        els[i].setAttribute("rows", 60);
    }
}

EXAMPLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM