【问题标题】:Get iframe contents with a jquery selector使用 jquery 选择器获取 iframe 内容
【发布时间】:2023-03-27 03:51:01
【问题描述】:

是否可以通过选择器访问 iframe 的内容?像这样的:

$("iframe::contents .my-foo")

我一直在访问我目前正在进行的项目的 iframe 内容,$("iframe").contents().find(".my-foo") 的输入变得有点乏味。

如果开箱即用的 jquery 中不存在此功能,是否有提供此功能的插件?如果不是我怎么写这样的插件?

【问题讨论】:

    标签: jquery iframe jquery-selectors sizzle


    【解决方案1】:

    我曾经遇到过这个问题,我觉得它很乏味。我从来没有找到如何编写这样的单个选择器的解决方案。

    即便如此,选择器仍然相当长。对我来说最明显的解决方案就是将它保存到一个变量中。

    var frame = $("iframe").contents();
    
    frame.find(".my-foo")
    ...
    

    这样更好吗?

    【讨论】:

    • 更多信息 - contents() = children() + plaintext 。有些人可能在想contents()有什么用,而我们可以只使用$('iframe').find('.my-foo'),那么请从w3schools.com/jquery/traversing_contents.asp阅读The contents() method can also access the HTML of an iframe, if it is in the same domain.
    【解决方案2】:

    直觉上,将所有内容打包到一个选择器中似乎更优雅,但事实是,即使有这样的选择器,从性能角度来看,用 find() 遍历更好。那么jQuery就不用对字符串进行解析分析了。

    【讨论】:

      【解决方案3】:

      为后代添加这里。我最终采用的解决方案是用一些自定义解析代码覆盖根 jquery 对象。像这样的:

      (function() {
          var rootjq = window.jQuery;
      
          var myjq = function(selector, context) {
              if(selector.indexOf("::contents") === -1) {
                  return rootjq(selector, context);
              } else {
                  var split = selector.split("::contents");
      
                  var ifrm = split[0];
                  var subsel = split.splice(1).join("::contents");
      
                  var contents = rootjq(ifrm, context).contents();
      
                  // Recursive call to support multiple ::contents in a query
                  return myjq(subsel, contents);
              }
          };
          myjq.prototype = myjq.fn = rootjq.fn;
      
          window.jQuery = window.$ = myjq;
      })();
      

      注意,css中的双冒号(::)表示select pseudo element,而单冒号表示通过伪类选择。

      【讨论】:

        【解决方案4】:

        您可以创建自己的自定义选择器。喜欢:

        $.extend($.expr[':'], {
            contents: function(elem, i, attr){
              return $(elem).contents().find( attr[3] );
            }
        });  
        

        用法应该是这样的

        $('iframe:contents(.my-foo)').remove(); 
        

        【讨论】:

        • 出于好奇,为什么要使用$.extend?为什么不直接像这样添加属性:$.expr[":"].contents = function(...) { ... }
        • 这个答案不起作用。我正在寻找 $("iframe").contents().find(".my-foo") 的替代品。挂在$.expr[':'] 上的函数就像过滤器一样。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-02-07
        • 2012-03-11
        • 1970-01-01
        • 2015-10-25
        • 2018-02-12
        • 2013-11-28
        • 1970-01-01
        相关资源
        最近更新 更多