簡體   English   中英

jQuery .html不能單擊按鈕

[英]jQuery .html a button can't be hit

有人可以向我解釋為什么當我通過jQuery添加按鈕時

$("#foo").html("<button id='hello'>Hello</button>");

我實際上嘗試過.on,.load但沒有任何改變...

當我單擊它時,他不起作用,實際上是在使用它與套接字交互,因此,當我單擊它時,它想對我的套接字服務器說些什么,但是按一下按鈕就什么都不做!

為什么我們不能按按鈕? 可能是因為使用此方法時他沒有出現在源代碼中(右鍵單擊)?

編輯我的示例代碼:

socket.emit('setContainer', "<button id='hello'>Hello</button>");

client.js

socket.on('setContainer', function(data)    {
    $('#container').html(data); 
});

在這里,套接字服務器將按鈕發送到html,當我按下此按鈕時,它應該啟動簡單的console.log事件

$('#essai').on("click", function() {
    console.log('123');
    //start answer to socket but button doesn't work
    socket.emit('helloBack', "123");
});

但是我不知道為什么當我們單擊按鈕就像鎖定按鈕或其他東西時按鈕在這里沒有任何作用(當我單擊按鈕時我看不到點擊效果)

動態添加按鈕時,需要直接在其上附加事件處理程序

 var button = $('<button id="hello">Hello</button>'); button.click(function() { console.log('hello'); }); $("#foo").html(button); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <div id="foo"></div> 

使用on()進行委派

 $("#foo").html("<button id='hello'>Hello</button>"); $(document).on('click', 'button', function(){ console.log('hello'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <div id="foo"></div> 

您應該使用.delegate()方法,以便將處理程序附加到尚不在DOM中的節點。

好的,我的問題解決了,這是解決方法:(示例)foo是包含由jQuery添加的#hello按鈕ID的div。

$('#foo').on('click', '#hello', function() {
    socket.emit('helloBack', {
        response:   "hello"
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM