gpt4 book ai didi

javascript - 在 JavaScript 中调用函数而不是触发(头脚本是 jQuery 和 jQuery Mobile)

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:06:24 25 4
gpt4 key购买 nike

我有一个这样的页面(index.php):

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
<?php //add .min.js file when all programming done ?>
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/_jquery.mobile-1.4.0.css">

<script src="js/_jquery-2.1.0.js" type="text/javascript"></script>
<script src="js/_jquery.mobile-1.4.0.js" type="text/javascript"></script>

<script src="js/main.js" type="text/javascript"></script>
<script src="js/sign.js" type="text/javascript"></script>
</head>
<body>
<div data-role="page">
<div data-role="header" id="nav"><?php include_once 'nav.ui.php'; ?></div>
<div data-role="main" class="ui-content" id="ui">

<input type="button" id="optionUpdate">

</div>
<div data-role="footer" id="footer"><?php include_once 'footer.ui.php'; ?></div>
</div>
</body>
</html>

在 main.js 中我有:

$('#optionUpdate').click(function () {
optionUpdate();
});

function optionUpdate() {
alert('hi');
}

问题是:当我点击按钮时,事件没有运行。但是如果使用 optionUpdate();onclick 事件添加到按钮,有效!为什么?我该如何解决这个问题?

最佳答案

在 jQuery Mobile 中,您需要将函数包装在 page events 中不在 .ready() 中。后者针对每个文档触发一次,其中页面事件针对每个页面/ View 触发。

如果您使用启用了 Ajax 的 jQuery Mobile 并且有多个页面或加载外部页面,如果您使用 .ready(),其中的函数将只执行一次。

Important: Use $(document).bind('pageinit'), not $(document).ready():

The first thing you learn in jQuery is to call code inside the $(document).ready() function so everything will execute as soon as the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the contents of each page into the DOM as you navigate, and the DOM ready handler only executes for the first page. To execute code whenever a new page is loaded and created, you can bind to the pageinit event. This event is explained in detail at the bottom of this page.

相当于 jQuery Mobile 中的 .ready()pagecreate (pageinit 自 1.4 起已弃用)。在 pagecreate 中包装函数可确保在 pagecreate 事件发生时触发这些函数。

$(document).on("pagecreate", function () {
$('#optionUpdate').on("click", function () {
optionUpdate();
});

function optionUpdate() {
alert('hi');
}
});

您可以将特定功能绑定(bind)到特定页面,方法是将事件委托(delegate)给该页面

$(document).on("pagecreate", ".selector or #page_ID", function () {
/* functions for this page only */
});

Demo

关于javascript - 在 JavaScript 中调用函数而不是触发(头脚本是 jQuery 和 jQuery Mobile),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21688150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com