dro*_*oob -1 javascript jquery onclick undefined
我遇到onclick问题,特别是下面代码中的onclick ="Foo()".点击后,我得到了未定义,但我已将功能包含在顶部,甚至在功能之外.
$( document ).ready(function() {
function Foo() {
console.log('clicky click click');
document.getElementById('categoryBubble').style.display = 'none';
}
$('.mutliSelect select').on('change', function() {
var title = $(this).closest('.mutliSelect').find('option').val();
title = $(this).val() + "";
if ($(this).is(':selected')) {
// the code for if goes here
} else {
console.log('im working here #2');
var html = '<span id="categoryBubble" title="' + title + '">' + title + '</span>' + '<span onclick="Foo()" class="Xout">x</span>';
$('.multiSel').append(html);
$(".hida").hide();
}
});
});
Run Code Online (Sandbox Code Playgroud)
Foo() (这不是一个构造函数,所以它不应该以大写字母开头命名)是本地作用于你传递给准备好的匿名函数.
然后onclick事件处理程序寻找被调用的东西Foo,它找不到它,因为它不在正确的范围内.
不要使用内部事件属性,它们有各种令人讨厌的问题,其中之一就是你几乎被迫使用全局变量.
使用jQuery函数生成HTML而不是将字符串混合在一起.使用jQuery on方法而不是onclick属性绑定事件处理程序.
$(function() {
function foo() {
console.log("clicky click click");
document.getElementById("categoryBubble").style.display = "none";
}
$(".mutliSelect select").on("change", function() {
var title = $(this)
.closest(".mutliSelect")
.find("option")
.val();
title = $(this).val() + "";
if ($(this).is(":selected")) {
// the code for if goes here
} else {
console.log("im working here #2");
var span = $("<span />")
.attr("id", "categoryBubble")
.attr("title", title)
.text(title);
var other_span = $("<span />")
.on("click", foo)
.addClass("Xout")
.text("x");
$(".multiSel").append(span);
$(".multiSel").append(other_span);
$(".hida").hide();
}
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
151 次 |
| 最近记录: |