我希望使用以字符串
开头的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);
我做错了什么?有一次,我得到了它的工作,但我不知道我做了什么来弄乱它......
答案 0 :(得分:0)
您的代码存在一些问题:
myArray
定义在.ready()
函数的外。只需在.ready()
函数内移动它就可以了。有关详细信息,请参阅Can't push items into array from anonymous callback function in Javascript。.text()
代替.text
来获取$(this)
的文字。 (使用函数而不是属性获取文本。).load()
而不是.ready()
所以,在所有这些修复后,您的代码应该是这样的:
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&PortalActualURL=https%3a%2f%2fwww.lionpath.psu.edu%2fpsc%2fCSPRD%2fEMPLOYEE%2fHRMS%2fc%2fSA_LEARNER_SERVICES.CLASS_SEARCH.GBL%3fpslnkid%3dPE_S201607061454417104632592&PortalContentURL=https%3a%2f%2fwww.lionpath.psu.edu%2fpsc%2fCSPRD%2fEMPLOYEE%2fHRMS%2fc%2fSA_LEARNER_SERVICES.CLASS_SEARCH.GBL%3fpslnkid%3dPE_S201607061454417104632592&PortalContentProvider=HRMS&PortalCRefLabel=Class%20Search&PortalRegistryName=EMPLOYEE&PortalServletURI=https%3a%2f%2fwww.lionpath.psu.edu%2fpsp%2fCSPRD%2f&PortalURI=https%3a%2f%2fwww.lionpath.psu.edu%2fpsc%2fCSPRD%2f&PortalHostNode=HRMS&NoCrumbs=yes&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>