不能在HTML站点中添加jQuery处理程序

Can't add jQuery handler to HTML site

本文关键字:jQuery 处理 程序 添加 HTML 站点 不能      更新时间:2023-09-26

我有一个单页网站:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.css" />
    <link type="text/css" rel="stylesheet" href="stylesheet.css" />
    <script src="http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.js"></script>
</head>
<body>
    <h1>Hello World</h1>
    <p>I'm hosted with GitHub Pages.</p>
    <div id="map"></div>
    <FORM>
        <INPUT id="but" Type="BUTTON" Value="About Me" />
    </FORM>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src=script.js></script>
</body>
</html>

我想添加一些处理程序按钮#but,并尝试使用脚本在script.js:

var mapClicked = function() {
    alert("Map!");
    // create a map in the "map" div, set the view to a given place and zoom
    //var map = L.map('map').setView([55.432, 37.654], 13);
}
$(document).ready(function() {
    $('#but').click(mapClicked());
});

但是当我在浏览器中运行这个html并点击按钮时,什么也没发生

通过引用函数的名称时将()添加到函数名。这将直接调用函数,返回值将被分配为click事件的回调。通过删除函数名的() (或者更确切地说是函数调用),函数被正确引用并在元素上发生click事件时被调用。

改变
$('#but').click(mapClicked());

$('#but').click(mapClicked); // <----- Removed ()