0

我的 div 的 id 如下:

<div id="text.header" class="countDiv"></div>
<div id="text.content" class="countDiv"></div> etc

我有两个数组。在第一个中,array1 = [1,2],在另一个中,我使用以下代码段存储所有 div 的 id

$(".countDiv").each(function(i){
    array2[i] = $(this).attr("id");
}

然后我使用.html()以下方法将值写入idiv 的 id:

for(var myCount = 0; myCount < array1.length; myCount++){
    $("#" + array2[i]).html(array1[i]);
}

问题是在所有情况下都很好,但是当我.在 id 之间使用时,代码不起作用。控制台上没有显示错误。

例如:当我使用 , 时,它工作得很好,但是当我使用 时,页面是空白的。代码不起作用。

我在这里做错了吗?任何帮助表示赞赏。

4

4 回答 4

2

如果您查看生成的选择器字符串的外观,您会看到此行导致的问题:

$("#"+array2[i])

假设 id 是text.header. 看看生成的选择器字符串变成了什么:

$('#text.header')

这个选择器将匹配一个 idtext和 class 的元素header。那不是你想要的。jQuery 解决方案是转义点,但更好的方法是只使用本机 DOM 方法并将其包装在 jQuery 对象中:

$(document.getElementById(array2[i]))

我没有在重复的问题中看到这种方法,所以我不妨把它贴在这里。

于 2013-06-06T05:21:16.393 回答
1

您已经提到myCount但没有使用它。jquery在使用时也会产生问题.id所以javascript在这里使用 selecting id

var array2=new Array();
var array1 = [1,2];
$(".countDiv").each(function(){
   array2.push($(this).attr("id"));
});

for(i=0; i<array1.length; i++){
    document.getElementById(array2[i]).innerHTML=(array1[i]);
}

小提琴 http://jsfiddle.net/gEScc/1/

于 2013-06-06T05:25:07.883 回答
0

表示 jQuery(和 CSS)中的.类选择器。考虑将其转义到\.

$("#" + array2[i].replace(".", "\\."))...
于 2013-06-06T05:17:06.497 回答
-1

。是的。

'。' 是 CSS 中的类路径分隔符,因此显然不能在类名中使用。

那是设计使然(CSS)。

于 2013-06-06T05:16:27.137 回答