2012-03-08 91 views
0

我有一些麻烦jQuery选择一些程序生成的div麻烦选择使用jQuery

我使用google visualization table显示,每页20个结果一些查询结果的工作程序生成的按钮。当查询返回超过20个结果(并且只有当结果超过20个时),分页按钮出现在搜索结果窗格的底部。

<div class="google-visualization-table-div-page"> 
    <div class="a-b-c a-d-e a-d-e-j a-d-e-o-p" title="" aria-disabled="true" 
    role="button" style="-moz-user-select: none;"> 
    <div class="a-b-c a-d-e-f-g"> 
     <div class="a-b-c a-d-e-h-g">&lt;&lt;</div> 
    </div> 
    </div> 
<div class="a-b-c a-d-e a-d-e-o-q" title="" role="button" 
style="-moz-user-select: none;" tabindex="0"> 
    <div class="a-b-c a-d-e-f-g"> 
    <div class="a-b-c a-d-e-h-g">&gt;&gt;</div> 
    </div> 
</div> 
</div> 
</div> 

我的目标是将这些相同的分页按钮添加到窗格的顶部。不幸的是,复制和粘贴结果窗格上方的那些div无法工作,所以我的计划是使用jquery的click事件来使顶部的复制/粘贴按钮以编程方式点击底部的按钮。

我的按钮与上面的div中的按钮完全相同,只是添加了id。

<div id="top_prev" class="a-b-c a-d-e a-d-e-j a-d-e-o-p" style="-moz-user-select: none;" role="button" aria-disabled="true" title=""> 

<div id="top_next" class="a-b-c a-d-e a-d-e-o-q" tabindex="0" style="-moz-user-select: none;" role="button" title=""> 

不幸的是,我试过的jquery没有工作,而我在调试时,我想我偶然发现了这个问题。这里是我的调试JQuery的:

$(document).ready(function() 
{ 
$("#top_prev").click(function(){ 
     if ($(".a-b-c a-d-e a-d-e-j a-d-e-o-p").length) { 
      alert("top_prev success"); 
     }else 
     { 
      alert("top_prev fail"); 
     } 
}); 

$("#top_next").click(function() { 
if ($(".a-b-c a-d-e a-d-e-o-q").length) 
{ 
    alert("top_next success"); 
}else 
{ 
alert("top_next fail"); 
} 
}); 

这将导致“top_next失败”或“失败top_prev”盒子正在生成这些div时甚至会出现。这些按钮的javascript和html甚至在之后生成生成结果窗格,因此底部按钮应该在顶部按钮之前生成。

我想我很难理解为什么这些选择器不工作。这里是我试过的原始的.click jquery:

$(document).ready(function(){ 
$("#top_prev").click(function(){ 
    $(".a-b-c a-d-e a-d-e-j a-d-e-o-p").click(); 
}); 

$("#top_next").click(function() { 
    $(".a-b-c a-d-e a-d-e-o-q").click(); 
}); 
}); 

回答

0

问题是因为你的选择器匹配底部的元素是错误的。

你应该使用;

$(document).ready(function(){ 
    $("#top_prev").click(function(){ 
     $(".a-b-c.a-d-e.a-d-e-j.a-d-e-o-p").not(this).click(); 
    }); 

    $("#top_next").click(function() { 
     $(".a-b-c.a-d-e.a-d-e-o-q").not(this).click(); 
    }); 
}); 

.foo .bar形式的选择器是匹配与类的bar它们与foo(the descendant selector)类的元素的后代的所有元素。相反,您应该使用.foo.bar,它会搜索类别为foobar的所有元素。

+0

那不点击自己呢?;) – Archer 2012-03-08 15:21:31

+0

@Archer:不要傻,这就是'not(this)'(now)检查的对象:P;) – Matt 2012-03-08 15:27:08

+0

为什么我没有发现:p – Archer 2012-03-08 15:27:38

0

另一种方法是克隆现有的按钮...

(我假设在这里,你提供的HTML是公正的分页按钮孤单。)

var $paging = $("google-visualization-table-div-page").clone(true); 
$("#containerID").append($paging); 

containerID将是添加到页面的div或跨度的ID和按钮将附加到该页面。

下面是克隆,并附加参考...