在jQuery选择器中增加id值

时间:2022-01-21 20:28:51

I have the following code:

我有以下代码:

$("#cc").on('hidden.bs.modal', function (e) {
  $("#cc iframe").attr("src", $("#cc iframe").attr("src"));
});

I would like to apply that to 10 different divs in my markup (#cc-1, #cc-2, #cc-3, etc...).

我想将它应用于我的标记中的10个不同的div(#cc-1,#cc-2,#cc-3等...)。

I tried using a for loop so I don't have to rewrite the same code 10 times by doing the following:

我尝试使用for循环,所以我不必通过执行以下操作重写相同的代码10次:

for (var i = 1; i < 11; i++) {

    $('"#cc-' + i + ' iframe"').on('hidden.bs.modal', function (e) {
        $('"#cc-' + i + ' iframe"').attr("src", $('"#cc-' + i + 'iframe"').attr("src"));
    });

}

The thing is, I don't know how to concatenate the variable i inside my jQuery selector with everything else.

问题是,我不知道如何将我的jQuery选择器中的变量连接到其他所有内容。

Please note that I need to target the iframe inside every #cc- div. This is the part what I'm getting trouble with. When adding the iframe after the concatenation of the #cc- with the variable i I get a syntax error.

请注意,我需要在每个#cc-div中定位iframe。这是我遇到麻烦的部分。在#cc-与变量i的串联之后添加iframe时,我得到语法错误。

I hope I made myself clear. Any clues in what I'm doing wrong?

我希望自己清楚明白。我做错了什么线索?

2 个解决方案

#1


4  

You should be able to concatenate a variable in a selector like you are doing, however you don't need to add quotations.

您应该能够像选择一样在选择器中连接变量,但是您不需要添加引号。

Change this:

改变这个:

 $('"#cc-' + i + ' iframe"')

To this:

对此:

 $('#cc-' + i + ' iframe')

Also you are forgetting to add a space infront of your iframe class.

此外,您忘记在iframe类前面添加空格。

Change this:

改变这个:

$('"#cc-' + i + 'iframe"')

To This:

对此:

$('#cc-' + i + ' iframe')

Complete Change:

完成变更:

for (var i = 1; i < 11; i++) {

    $('#cc-' + i + ' iframe').on('hidden.bs.modal', function (e) {
        $('#cc-' + i + ' iframe').attr("src", $('#cc-' + i + ' iframe').attr("src"));
    });

}

#2


0  

for (var i = 1; i < 11; i++) {
var mydiv="#cc-"+i;
    $("mydiv iframe").on('hidden.bs.modal', function (e) {
        $('"#cc-' + i + ' iframe"').attr("src", $('"#cc-' + i + 'iframe"').attr("src"));
    });

}

#1


4  

You should be able to concatenate a variable in a selector like you are doing, however you don't need to add quotations.

您应该能够像选择一样在选择器中连接变量,但是您不需要添加引号。

Change this:

改变这个:

 $('"#cc-' + i + ' iframe"')

To this:

对此:

 $('#cc-' + i + ' iframe')

Also you are forgetting to add a space infront of your iframe class.

此外,您忘记在iframe类前面添加空格。

Change this:

改变这个:

$('"#cc-' + i + 'iframe"')

To This:

对此:

$('#cc-' + i + ' iframe')

Complete Change:

完成变更:

for (var i = 1; i < 11; i++) {

    $('#cc-' + i + ' iframe').on('hidden.bs.modal', function (e) {
        $('#cc-' + i + ' iframe').attr("src", $('#cc-' + i + ' iframe').attr("src"));
    });

}

#2


0  

for (var i = 1; i < 11; i++) {
var mydiv="#cc-"+i;
    $("mydiv iframe").on('hidden.bs.modal', function (e) {
        $('"#cc-' + i + ' iframe"').attr("src", $('"#cc-' + i + 'iframe"').attr("src"));
    });

}