我的js文件中存在问题。 这是我的Js Code。
<script type="text/javascript">
$(document).ready(function()
{
$(".abc").click(function()
{
$(this).addClass('testingClass');
});
$(".testingClass").click(function()
{
alert("hiiiiiiiiiiiiiiiiii")
});
});
</script>
我的HTML:
<button class="abc">Demo</button>
当我在浏览器中加载此页面时,addClass函数成功执行并添加名为“testingClass”的新类。
但是当尝试再次单击该按钮(meens:class =“testingClass”)时,警报功能无效。错误是什么。
JS是否不支持频繁执行元素? 有人请帮帮我。
步骤..
答案 0 :(得分:1)
您需要event delegation
获取动态添加元素
$(document).on("click",".testingClass",function()
{
alert("hiiiiiiiiiiiiiiiiii")
});
答案 1 :(得分:1)
对于已更改的问题,您正在寻找类似的内容。 这是demo。
$('body').on('click', '.abc', function () {
// event attached to .abc
// updateTime is a method that takes context (this), current timestamp and a function
// we need to send the context so that we have access to the current
element inside the below function which is executed outside the scope
updateTime.call(this, new Date().getTime(), function (data) {
$(this).addClass('testingClass').removeClass('abc');
$('#log').append('Time: ' + data + 'from abc <br/>');
});
}).on('click', '.testingClass', function () {
// event attached to .abc
updateTime.call(this, new Date().getTime(), function (data) {
$(this).addClass('abc').removeClass('testingClass');
$('#log').append('Time: ' + data + ' from testingclass <br/>');
});
});
function updateTime(currentTime, successCallback) {
$.ajax({
context: this, // the context sent from the above methods is used here
url: '/echo/html/',
data: {
html: currentTime
},
method: 'post',
success: successCallback
});
}
使用.one()
可以帮助您在多次点击后仅附加一次事件。
每个事件类型的每个元素最多执行一次此处理程序。
我认为这就是你要找的东西。在添加类之后添加处理程序。
$(".abc").click(function(){
$(this).addClass('testingClass');
$(".testingClass").one('click', function() {
alert("hiiiiiiiiiiiiiiiiii");
});
});
$(document).ready(function() {
$(".abc").click(function() {
$(this).addClass('testingClass');
$(".testingClass").one('click', function() {
alert("hiiiiiiiiiiiiiiiiii");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="abc">Demo</button>