JavaScript:如何在字符串中设置变量

JavaScript:如何在字符串中设置变量,javascript,Javascript,我想对id以“id-”开头,后跟数字[e.g.id=“id-0”、id=“id-1”)的所有元素设置属性 <script type="text/javascript" > function Prepare() { var = 0 while(document.getElementById("id-{var}")) { document.getElementById("id-{var}").setAttribute("rows", "60");

我想对id以“id-”开头,后跟数字[e.g.id=“id-0”、id=“id-1”)的所有元素设置属性

<script type="text/javascript" >

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

</script>

函数Prepare(){
var=0
while(document.getElementById(“id-{var}”)){
document.getElementById(“id-{var}”).setAttribute(“行”,“60”);
var+=1
}

如何在JavaScript中设置这样的变量?

这应该可以完成以下任务:

<script type="text/javascript" >

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

</script>

函数Prepare(){
变量ct=0
while(document.getElementById(“id-”+ct)){
document.getElementById(“id-”+ct).setAttribute(“行”,“60”);
ct+=1
}
或者:

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

函数Prepare(){
对于(var ct=0;document.getElementById(“id-”+ct);ct++){
document.getElementById(“id-”+ct).setAttribute(“行”,“60”);
}

这将完成以下任务:

<script type="text/javascript" >

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

</script>

函数Prepare(){
变量ct=0
while(document.getElementById(“id-”+ct)){
document.getElementById(“id-”+ct).setAttribute(“行”,“60”);
ct+=1
}
或者:

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

函数Prepare(){
对于(var ct=0;document.getElementById(“id-”+ct);ct++){
document.getElementById(“id-”+ct).setAttribute(“行”,“60”);
}

根据您可以使用的兼容性:

函数准备(){
var els=document.queryselectoral(“[id^=id]”);

对于(var i=0;i,取决于您可以使用的兼容性:

函数准备(){
var els=document.queryselectoral(“[id^=id]”);

对于(var i=0;i
if(document.getElementById(“id-”+变量)){/**do stuff*/};
if(document.getElementById(“id-”+变量)){/**do stuff*/};
ct+=1相当于ct=ct+1或ct++@user:Gosh,真的吗?!@T.J.Crowder你每天都会学到新东西。哈哈,但是是的,这很有趣handy@Shawn31313:我的评论可能带有讽刺意味ct+=1相当于ct=ct+1或ct++@user:Gosh,真的吗?!@T.J.Crowder你每天都会学到新东西。哈哈,但是是的,这很有趣handy@Shawn31313:我的评论可能带有讽刺意味