【问题标题】:Selector only knowing tbody and iterating选择器只知道 tbody 和迭代
【发布时间】:2009-12-16 00:20:21
【问题描述】:

这让我发疯...我正在尝试遍历表中的行。我知道 tbody 的类名。我可以只为 tbody 指定类并遍历行吗?比如……

<div class="dclass1" ...>
   <table summary="" style="margin-top: 0pt;">
     <thead ...>
     <tbody class="tbClass1" ..>
      ...
     <tbody class="tbClass2" ..>
       <tr ..> 
          ...
       <tr ...>
     </tbody>
...

如何循环(或仅指定选择器)class="tbClass2" 中的行?

【问题讨论】:

  • 我想我应该添加这个内容在 iframe 中(比如 id=myiframe)
  • 检查 iframe 合并的扩展答案。不要忘记如果 iframe 指向远程内容(不在同一个域上)将不起作用

标签: javascript jquery


【解决方案1】:

好的,您添加了要访问的数据位于 iframe 中的附加信息。正如我已经解释过的,以下代码仅在 iframe 内容与其嵌入的页面位于同一域中时才有效。

$(document).ready(function() {
    var iframe = $("iframe#myiframe");
    //wait for iframe to load
    $(iframe).load(function() {
        iframe = iframe.get(0);
        //handle browser specifics
        var oDoc = (iframe.contentWindow || iframe.contentDocument);
        if (oDoc.document)
            oDoc = oDoc.document;
        $("tbody.tbClass2 > tr", oDoc).each(function(index, element) {
            alert(index); //or do whatever
        });
    });
});

演示页面http://jsbin.com/afumi,其中包括http://jsbin.com/aqaxu(通过 iframe)。

如前所述,如果 iframe 指向远程内容,这将不起作用,因为浏览器将拒绝访问 iframe DOM

例如

<iframe src="http://www.google.com">...</iframe>

$("tbody.tbClass2 > tr")

现在你可以做

$("tbody.tbClass2 > tr").each(function(index, element) {
    //do whatever iterating over all TRs
});

【讨论】:

  • 查看上面的评论..是 iframe 导致问题吗?
【解决方案2】:

试试:

$(".tbClass2").children("tr");

然后您可以使用 eg 进行迭代:

$(".tbClass2").children("tr").each( function() {
  // do something here
});

【讨论】:

  • 似乎不起作用。这些元素在 iframe 中的事实是否会导致它无法选择这些对象?
  • 哇!当然,如果 iframe 发挥作用,这很重要。这改变了整个事情。 javascript 是否也在 iframe 本身中运行?如果不是,则 iframe 至少必须指向 (src) 同一域上的某些内容,否则浏览器将拒绝访问 iframe 内容。
  • @GregH:您应该在问题中添加非常重要的信息。
猜你喜欢
  • 2020-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-12
  • 2011-03-24
  • 1970-01-01
  • 2013-07-30
  • 2017-07-02
相关资源
最近更新 更多