首页 > 解决方案 > 单击带有 jQ​​uery 的按钮没有动作

问题描述

我被一个按钮卡住了,不明白为什么它不起作用。

$('#full-london').on('click', () => {
weatherPage.render('London');
});

'#full-london' 是我的按钮的 ID

weatherPage.render 启动了一些 jQuery 代码来改变我的首页。这在其他情况下进行了测试,并且工作正常。

这是按钮:

<a id="full-london" class="btn btn-dark">Full forecast</a>

知道有什么问题吗?

这是使用 weatherPage.render 的搜索按钮的其他情况,并且可以正常工作:

$('#search-city-button').on('click', () => {
    const searchString = $('#search-city-input').val();
    weatherPage.render(searchString);
});

searchString 是搜索输入

 <div id="search">
      <input type="text" id="search-city-input">
      <a id="search-city-button" class="btn btn-danger">Search</a>
 </div>

这是weatherPage.render();做什么https://pastebin.com/PLgrrYQ0

标签: javascriptjqueryonclick

解决方案


这很有意义!

您正在动态添加按钮,因此当时 JS 解析$('#full-london').on('click',...时页面上没有按钮,因此无法将事件附加到它。

function setEvents() {
  $('#full-london').on('click', () => {
    weatherPage.render('London');
  });
}

在您的 JS 模块中创建一个函数(如),并在将按钮添加到页面setEvents调用该函数。


推荐阅读