简体   繁体   English

更改多个输入字段的值

[英]changing values of multiple input fields

Let's say I have a few divs with IDs like "div1", "div2", "div3" and so on. 假设我有几个div,其ID如“div1”,“div2”,“div3”等等。

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. 但如果我喜欢30个div,这会很烦人。 I'm trying to use "for" but it's not working: 我正在尝试使用“for”但它不起作用:

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). 当我使用.val()函数(jQuery)时,我得到同样的东西。

What am I doing wrong in this case, guys? 在这种情况下我做错了什么,伙计们? :) :)

You have a few things wrong. 你有一些错误。 first, don't use # in getElementById() . 首先,不要在getElementById()使用# second is that div elements doesn't have .value attribute, use innerHTML instead.. the third is that you're trying to access multiple elements by their id instead of creating a class shared by all of them. 第二个是div元素没有.value属性,而是使用innerHTML 。第三个是你试图通过id访问多个元素而不是创建一个由所有元素共享的类。 Code example: 代码示例:

HTML: 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: (tagged in question - easiest example) jQuery :(标记有问题 - 最简单的例子)

$(function(){
    $('.myDiv').text('something');
});

You may use jquery each function but first you need to declare an array of div IDs for which you want to assign the value. 您可以使用jquery每个函数,但首先需要声明要为其分配值的div ID数组。

jQuery.each( [ "one", "two", "three", "four", "five" ], function() {
$('#' + this).text('value');
});

Or as said by Yotam, you may give a common class and just write 或者如Yotam所说,你可以给一个普通的课,然后写

$('.className').text('value');

You could do something simple like this: 你可以做这样简单的事情:

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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