【问题标题】:How can I convert a button click with an onload event?如何使用 onload 事件转换按钮单击?
【发布时间】:2012-10-12 16:49:59
【问题描述】:

如何转换此脚本以触发 onload 而不是使用按钮单击?我试图理解这一点,但它并没有陷入困境。

<script type="text/javascript"> 
jQuery(function($){
    // unordered list
    $('button.item').click(function(){
        $('ul').foo();
    });
    
});
</script>
</head>     
<body>
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
</ul>
<button class="item">foo</button>

【问题讨论】:

  • 你想在你的列表上运行一个名为foo的jQuery插件,加载?只需将其从点击事件中取出即可
  • jQuery(function() { /* body */ }) 的主体已经在DOMReady 上执行,这或多或少等同于(通常优于)load

标签: javascript html jquery html-lists jquery-events


【解决方案1】:

使用load 函数让函数在 onload 事件上执行:

<script type="text/javascript"> 
$(window).load(function(){
       $('ul').foo();    
});
</script>

请注意,如果您不需要加载所有内容(例如子元素,主要是图像),通常最好在 dom 准备好后立即使用 $(callback) 执行您的函数:

<script type="text/javascript"> 
$(function(){
       $('ul').foo();    
});
</script>

【讨论】:

  • 想象一下,load 事件是deprecated! :)
  • @pst :当 dom 准备好时,您的构造会触发,而不是 onload 事件。
【解决方案2】:

你可以这样使用:

<body>
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
</ul>
<script type="text/javascript"> 
$(document).ready(function() {
  $('ul').foo();
});
</body>

最好在文件末尾调用它,就在关闭&lt;body&gt;标签之前。

而函数$(document).ready(function(){... 是您在页面加载时需要执行某些操作时使用的函数。

我建议你查看 w3schools 中的 jQuery 教程:http://www.w3schools.com/jquery/default.asp

Document.ready 比 window.onLoad 反应更快

【讨论】:

  • 谢谢!!!我在这里尝试了所有方法..这似乎对我来说更便携
  • 确实不需要在文档末尾使用.ready()。脚本运行时 dom 已经完全加载...
【解决方案3】:
 <script type="text/javascript">
function abc() {
    alert('ok');
}
window.onload = abc;
</script>

【讨论】:

  • 你也可以这样做 但 WINDOW.ONLOAD 更好
  • 如果你使用 jquery,window.onload 可能已经包含一个函数并且你正在覆盖它......
  • 是的,如果使用 jquery,那么它非常简单 $(document).ready(yourfunction () {// Page is loaded.});
猜你喜欢
  • 2012-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-16
  • 1970-01-01
相关资源
最近更新 更多