Cha*_*son 26 html javascript css jquery
所以,我在一个范围内创建了一个删除"按钮",但由于某种原因,我无法启动.click().有任何想法吗?我是jQuery的新手,我觉得这很明显.我在Chrome和Safari中测试过没有运气.
CSS:
.delete_button {
cursor:pointer;
color: #fff;
border: 1px solid #FFF;
border-radius: 15px;
background: #AAA;
font-size: 8px;
line-height: 0px;
padding: 0px 2px 0px 2px;
}
Run Code Online (Sandbox Code Playgroud)
HTML/PHP:
<span class="delete_button" id="delete_<? echo $some_id; ?>">X</span>
Run Code Online (Sandbox Code Playgroud)
jQuery的:
$(document).ready(function() {
$('.delete_button').click(function() {
var transaction_id = $(this).attr('id').replace('delete_','');
alert("Delete transaction #" + transaction_id);
return false;
});
});
Run Code Online (Sandbox Code Playgroud)
Tus*_*har 78
使用.on()
您的span是动态添加的,因此在DOM就绪或页面加载时不会出现.
所以你必须使用事件委派
句法
$( elements ).on( events, selector, data, handler );
Run Code Online (Sandbox Code Playgroud)
像这样
$(document).on('click','.delete_button',function(){
// code here
});
Run Code Online (Sandbox Code Playgroud)
要么
$('parentElementPresesntAtDOMready').on('click','.delete_button',function(){
// code here
});
Run Code Online (Sandbox Code Playgroud)
你的代码变成了
$(document).ready(function () {
$(document).on('click', '.delete_button', function () {
var transaction_id = $(this).attr('id').replace('delete_', '');
alert("Delete transaction #" + transaction_id);
return false;
});
});
Run Code Online (Sandbox Code Playgroud)
Ant*_*ton 11
It seems like the span is dynamically created, you need to use event delegation. Bind it to the closest static parent or document
$(document).on('click','.delete_button',function(){
/*Your code*/
});
Run Code Online (Sandbox Code Playgroud)