javascript - 按钮单击事件位于另一个按钮单击事件中?

标签 javascript jquery

我正在使用 Chartjs 结合对第三方数据库的 ajax 调用来绘制一些基本的数据图表。

当用户搜索某个项目并通过单击按钮触发搜索时,会在新页面上自动生成默认图表。我希望用户能够自定义图表(即将其从线更改为山或时间间隔)。

我已经在 html 上创建了所有按钮和所有 ajax 调用并测试了它们。他们都工作。不起作用的是搜索词。

搜索到的术语的值保存在初始搜索按钮单击中,但对图形的每次修改(及其相应的按钮单击)都不在默认按钮单击内部,而是在默认按钮单击外部,因此它们无权访问搜索词变量的值。

我认为嵌套按钮点击是不好的编码习惯,但我不确定如何获取搜索词的值。

$('#searchBTN').on('click', function(){
        event.preventDefault();
        // get user input
        var searchTerm = $('#searchInput').val();

        $('#searchInput').val('');

enter image description here

最佳答案

<强> Event Delegation (在事件冒泡链的上方设置事件处理程序的过程,以便它可以拦截所有后代元素触发的事件)就是您在这里所需要的。

这是一个例子:

// Set up the event on a parent element of all the inputs/buttons whatever
// But indicate (via the second argument to the .on() method), what element(s)
// to actually run the callback on
$(document).on('input', "input", function(){
  // No matter which input you actually type in, it's handled with
  // this one event callback, so there is a single point to handle 
  // all of them.
  console.log("You entered: " + $(this).val() + " into " + this.id);        
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input1">
<input id="input2">
<input id="input3">
<input id="input4">
<input id="input5">

关于javascript - 按钮单击事件位于另一个按钮单击事件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49180561/

相关文章:

javascript - 重新格式化 javascript 以适应 google-closure-compiler 的命名空间展平

javascript - url 完成加载 View 后删除 localstorage

javascript - 是否可以设置跨域 iframe 内容的样式?

javascript - 让 jQuery 在 Rails 应用程序上运行

javascript - div的循环运动

javascript - 单选按钮组

php - 在提交之前通过 Javascript 进行一些表单验证是否明智?

javascript - JS顺利交换图像

javascript - jQuery SyntaxError 需要帮助修复

javascript - 使用 jquery 对具有单个最大值的多个文本框值中的字符进行计数