我正在用 javascript 使用 Accordion 菜单,这是代码
<body>
<script>
$(function() {
$( "#accordion" ).accordion();
});
</script>
<div style="width:50%;float: left;height:50%;" id="accordion"></div>
<script>
var html = '';
var text = 'Lorem ipsum dolor sit amet ..';
// first we generating our html in the loop
for(var i=0 ; i<6 ; i++) {
html += '<h3>Section ' + i + '</h3>' + '<div><p>' + text + '</p></div>';
}
document.getElementById("accordion").innerHTML = html;
// next we're inserting html into block with ID accordion
</script>
它工作正常,但是当我把它放在一个函数中时,它不起作用 此代码不起作用
<body onload="test()">
<script>
$(function() {
$( "#accordion" ).accordion();
});
</script>
<div style="width:50%;float: left;height:50%;" id="accordion"></div>
<script>
function test(){
var html = '';
var text = 'Lorem ipsum dolor sit amet ..';
// first we generating our html in the loop
for(var i=0 ; i<6 ; i++) {
html += '<h3>Section ' + i + '</h3>' + '<div><p>' + text + '</p></div>';
}
document.getElementById("accordion").innerHTML = html;
}
</script>
我怎样才能使 Accordion 菜单在函数中工作?
最佳答案
它在函数内部时不起作用的原因是因为您没有显式调用该函数。 在方便的地方定义该函数,然后从 documentOnLoad 函数中调用它,以便脚本在执行时获取所有引用的元素。
编辑:不敢相信我错过了 onload="test()"
行。
这让我觉得原因可能是执行顺序。您在定义它之前调用测试,这可能是一个原因。在顶部某处(onload=test()
之前)定义测试函数,这可能会起到作用。
同样从 $(function()...) 调用测试可能是个好主意,因为它肯定会在 documentReady
之后和调用 .accordion()
函数之前执行
附言将此视为建议而不是具体答案,因为我无法自己测试我的答案,因为我在工作场所。
关于javascript - Accordion 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30128602/