jquery:如何找到具有相同类的子div的索引

时间:2012-12-13 18:45:33

标签: jquery class indexing parent-child

这是问题;我有一个div,里面包含子div,我似乎无法访问子div。我需要的是为每个子div找到带有.eq90的索引。

以下是生成父级的代码。

function makeSmallBlockdiv ()
{
var smallBlock = $('<div class="SmallBlock EditBlock"></div>').appendTo("#canvas");
smallBlock.draggable({containment: "#canvas", scroll: false, grid: [10, 10]}, {cursor: "move", cursorAt: {top: 125, left: 150}})
smallBlock.append('<div class="article_title EditBlock fontCenter fontBold font24">Article Title</div>')
smallBlock.append('<div class="article_Image"><img style="width: 250px;" src="<? echo $image1 ?>"></div>')
smallBlock.append('<div class=" article_text font14"><? echo substr($article_text, 0, 200) ?></div>')   
}

可以根据需要经常调用此函数来创建更多父div。 到目前为止我所尝试的是以下内容:

$(".article_text").click(function() {
  alert("Index: " + $(this).index());
});

我已将其包含在函数ready()中并进行更改。这段代码来自我在http://jsfiddle.net/fY6SU/48/

找到的小提琴

小提琴代码完美无缺,但我的代码无效。当我用firebug查看我的html时,我可以看到div正确地创建了gettig。我很难过,我刚刚开始使用jquery,这无济于事。

任何建议都将不胜感激。

由于

克里斯

4 个答案:

答案 0 :(得分:2)

$(".article_text").click(function() {
  alert("Index: " + $(this).index());
});

选择器只选择类'article_text',而你生成的html只包含一个带有'article_text'类的div,所以解决方案是将一个类添加到具有相同名称的div或使用多重选择器,像这样:

$(".article_text, .article_Image, .article_title, .SmallBlock").click(function() {
  alert("Index: " + $(this).index());
});

答案 1 :(得分:0)

您的解决方案在您的班级名称中。 $(“。article_text”)只选择最后一个div,并考虑按照示例小提琴中的类名重命名

答案 2 :(得分:0)

What I need is to find the index with .eq90 for each of the child divs.

下面:

var ninetyChildren = new Array(); //create an array to hold the children
$(".parent").each(function() { //loop through each parent
    var ninety = $(this).children().eq(89).text(); //get index of 90 - eq starts with 0
    ninetyChildren.push(ninety); //add 90th index to array
});

$.each(ninetyChildren, function(i, data){ //loop through 90th indexes
alert(i +" "+ data); //alert each 90th index
});
​

希望这是你想要的。 Mock Demo

答案 3 :(得分:0)

我能够弄清楚如何获得兄弟姐妹的索引()。

以下是我用来找到它们的代码。

$("div").children(".article_text").eq(3).css("color", "red");

css选择器只是作为视觉辅助来确认其工作。

感谢所有帮助过我的人。