无法在我的HTML中找到按钮

时间:2018-03-07 19:23:57

标签: javascript jquery html

我在javascript中练习MVC,并且我试图将控制器中的事件处理程序附加到按钮上。首先,我创建视图,在它的构造函数中,我加载外部HTML。然后,在控制器构造函数中,我尝试执行find("#myButton")以找到我的按钮,然后附加一个事件监听器。这是我的尝试:

的index.html:

<div id="welcome"></div>

JS / app.js:

var welcome = $("#welcome");
var welcomeView = new WelcomeView(welcome, model);
var welcomeController = new WelcomeController(welcome, model, generalController);

JS /视图/ welcomeView.js:

var WelcomeView = function(container, model){
    var container = container;
    var model = model;

    container.load("welcome.html");

    this.show = function(){
        container.style.display = "block";
    }

    this.hide = function(){
        container.style.display = "none";
    }
}

welcome.html:

<button type="button" class="btn btn-default" id="myButton">Create new dinner</button>

JS /控制器/ welcomeController.js:

var WelcomeController = function(container, model, generalController){
    var container = container;
    var model = model;

    var createButton = container.find("#myButton");

    createButton.click( function() {
        alert("entered");
        generalController.showScreen("DISHSEARCH");
    } );
}

当我点击按钮时,没有任何反应。当我在控制器中没有jQuery的情况下尝试时:

createButton[0].onclick = function(){
    alert("hello");
};

我收到错误:

welcomeController.js:7 Uncaught TypeError: Cannot set property 'onclick' of undefined
    at new WelcomeController (welcomeController.js:7)
    at HTMLDocument.<anonymous> (app.js:30)
    at fire (jquery.js:3119)
    at Object.fireWith [as resolveWith] (jquery.js:3231)
    at Function.ready (jquery.js:3443)
    at HTMLDocument.completed (jquery.js:3474)

所以找到按钮元素似乎有些问题,但我无法弄清楚!这有什么不对?

2 个答案:

答案 0 :(得分:0)

@skobaljic有正确的解决方案。使用.on()解决了问题:

JS /控制器/ welcomeController.js:

container.on('click', "#myButton", function() {
        alert("Success!");
        generalController.showScreen("DISHSEARCH");
    })

答案 1 :(得分:0)

在您的index.html中使用welcome.html和welcome div,这很好用: (加载函数有一个回调函,通知您加载已完成)。如其他提到的;这是一个异步任务。

$(function() {
    $("#welcome").load("welcome.html", function() {
        $('#myButton',this).on("click",function() {
            alert("clicked");
        });
    });
});

也可以同步加载,$.ajax({async:false,...或者这个香草:

var request = new XMLHttpRequest();
request.open('GET', 'welcome.html', false);  // `false` makes the request synchronous
request.send(null);
if (request.status === 200) {
  console.log(request.responseText);
}