迭代iframe中的所有ID

时间:2017-05-23 04:13:19

标签: javascript jquery iframe

我希望使用以字符串

开头的ID迭代iframe中的所有跨度
var myString = "starts with this id";
var myArray = [];
  $('#ifr').ready(function(){
    $(this).contents().find('span[id^="myString"]').each(function(i, obj) {
      myArray.push($(this).text);
    });
  });
  console.log(myArray);

我做错了什么?有一次,我得到了它的工作,但我不知道我做了什么来弄乱它......

1 个答案:

答案 0 :(得分:0)

您的代码存在一些问题:

  1. myArray定义在.ready()函数的。只需在.ready()函数内移动它就可以了。有关详细信息,请参阅Can't push items into array from anonymous callback function in Javascript
  2. 您需要使用.text()代替.text来获取$(this)的文字。 (使用函数而不是属性获取文本。)
  3. 您需要等待iframe加载.load()而不是.ready()
  4. 所以,在所有这些修复后,您的代码应该是这样的:

    JS:

    $(document).ready(function() {
      $('#ptifrmtgtframe').load(function() {
        var myArray = [];
        $(this).contents().find('span[id^="MTG_INSTR$"]').each(function(i, obj) {
          myArray.push($(this).text());
        });
        console.log(myArray);
      });
    });
    

    HTML:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <iframe id="ptifrmtgtframe" name="TargetContent" title="Main Content" frameborder="0" scrolling="auto" onload="ptrc.onLoadTC()" src="https://www.lionpath.psu.edu/psc/CSPRD/EMPLOYEE/HRMS/c/SA_LEARNER_SERVICES.CLASS_SEARCH.GBL?pslnkid=PE_S201607061454417104632592&amp;PortalActualURL=https%3a%2f%2fwww.lionpath.psu.edu%2fpsc%2fCSPRD%2fEMPLOYEE%2fHRMS%2fc%2fSA_LEARNER_SERVICES.CLASS_SEARCH.GBL%3fpslnkid%3dPE_S201607061454417104632592&amp;PortalContentURL=https%3a%2f%2fwww.lionpath.psu.edu%2fpsc%2fCSPRD%2fEMPLOYEE%2fHRMS%2fc%2fSA_LEARNER_SERVICES.CLASS_SEARCH.GBL%3fpslnkid%3dPE_S201607061454417104632592&amp;PortalContentProvider=HRMS&amp;PortalCRefLabel=Class%20Search&amp;PortalRegistryName=EMPLOYEE&amp;PortalServletURI=https%3a%2f%2fwww.lionpath.psu.edu%2fpsp%2fCSPRD%2f&amp;PortalURI=https%3a%2f%2fwww.lionpath.psu.edu%2fpsc%2fCSPRD%2f&amp;PortalHostNode=HRMS&amp;NoCrumbs=yes&amp;PortalKeyStruct=yes" style="width: 626px; height: 593px;">
      <span class="PSLONGEDITBOX" id="MTG_INSTR$1">I want this text</span>
      <br>
      <span class="PSLONGEDITBOX" id="MTG_OTHER">But not this text</span>
    </iframe>