0

Let's say I have a few divs with IDs like "div1", "div2", "div3" and so on.

What I am doing now is:

document.getElementById('#div1').value='something';
document.getElementById('#div2').value='something';
document.getElementById('#div3').value='something';

but this gets annoying if I have like 30 divs. I'm trying to use "for" but it's not working:

for(var i=1; i<31; i++) {
    document.getElementById('#div'+i).value='something';
}

I'm getting the same thing when I use the .val() function (jQuery).

What am I doing wrong in this case, guys? :)

4

3 に答える 3

2

いくつか間違っています。#まず、で使用しないでくださいgetElementById()。2 つ目は、要素に属性divがないことです。代わりに使用してください。3 つ目は、すべての要素で共有されるクラスを作成するのではなく、ID で複数の要素にアクセスしようとしていることです。コード例:.valueinnerHTML

HTML:

<div id="div1" class="myDiv"></div>
<div id="div2" class="myDiv"></div>
<div id="div3" class="myDiv"></div>
<div id="div4" class="myDiv"></div>
<div id="div5" class="myDiv"></div>
<div id="div6" class="myDiv"></div>
...

jQuery: (問題のタグ付け - 最も簡単な例)

$(function(){
    $('.myDiv').text('something');
});
于 2013-07-07T15:32:07.940 に答える
0

次のような簡単なことを行うことができます。

<html>
<head>
    <title>Sample</title>
    <script type="text/javascript">
        function textDiv() {
            var totalDivs = document.getElementsByTagName("div").length 
            for(var i =0; i<totalDivs; i++)
            { 
                document.getElementById("div" + [i]).innerHTML = "Some Thing as a Text"

            }

        }
    </script>
</head>
<body onload="textDiv();">
    <div id="div0"></div>
    <div id="div1"></div>
    <div id="div2"></div>
    <div id="div3"></div>
    <div id="div4"></div>
</body>
</html>
于 2013-07-07T15:48:33.380 に答える