如何将点击处理程序/任何事件处理程序附加到我的对象或模块

时间:2018-07-29 02:18:17

标签: javascript jquery node.js

我想将事件处理程序附加到我不知道如何实现的模块上。

以下是我的模块:

var globalModule = {

  name:'Banana on princess bed',

     init:function(){
         alert('Initialize');
     },

     getName:function(){
        return this.name; 
     }
}

上面的module我将为我的应用程序的每一页加载,或者说在index页(每隔一页可用)加载

假设这是page 1(除索引页外),我想听按钮单击

<button id="button1">button 1</button>

$('#button1').on('click',function(){
    // execute some code
});

问题:我如何处理button1 click中的globalModule,并如何处理

var globalModule = {

  name:'Banana on princess bed',
    
     init:function(){
         alert('Initialize');
     },

     getName:function(){
        return this.name; 
     }
}

globalModule.init();

var name = globalModule.getName();

console.log(name);

1 个答案:

答案 0 :(得分:1)

那么,为什么您认为在globalModule中声明单击事件还不够呢? 请告诉我详细信息。

var globalModule = {

  name:'Banana on princess bed',
    
     init:function(){
         alert('Initialize');
         // Attach an event.
         $('.common1').on('click', function() {
             console.log('target-modal : ' + $(this).data('targetModal'));
         });
         $('.modal-submit').on('click', function() {
             // you need to manage to work properly.
             // Get root, then find parameter.
             // Of course, If you use form and prevent submit,
             // jquery serializeArray() is a good option.
             var thisModal = $(this).closest('.modal-root');
             console.log(thisModal.find('.param1').val());
             console.log(thisModal.find('.param2').val());
             console.log('go ajax : ' + $(this).data('url'));
         });
     },
     getName:function(){
        return this.name; 
     }
}

globalModule.init();

var name = globalModule.getName();

console.log(name);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

■other page1
<input class="common1" id="page1-common1" type="button" value="Common Button?" data-target-modal="modal1" data-url="[1]if ajax url is differenc, you need it">
<div id="modal1" class='modal-root'>
    <input type="text" value="page1-param1" class="param1">
    <input type="text" value="page1-param2" class="param2">
    <input class="modal-submit" type="button" value="submit1" data-url="[1]if ajax url is differenct, you need it">
</div><br>
■other page2
<input class="common1" id="page2-common1" type="button" value="Common Button?" data-target-modal="modal2">
<div id="modal2" class='modal-root'>
    <input type="text" value="page2-param1" class="param1">
    <input type="text" value="page2-param2" class="param2">
    <input class="modal-submit" type="button" value="submit2" data-url="[2]if ajax url is differenc, you need it">
</div>