Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 必须监控多个元素时的头部。在tbody中有1000行的数据表上,第一个代码示例将处理程序附加到1000个元素_Javascript_Jquery_Events_Unobtrusive Javascript - Fatal编程技术网

Javascript 必须监控多个元素时的头部。在tbody中有1000行的数据表上,第一个代码示例将处理程序附加到1000个元素

Javascript 必须监控多个元素时的头部。在tbody中有1000行的数据表上,第一个代码示例将处理程序附加到1000个元素,javascript,jquery,events,unobtrusive-javascript,Javascript,Jquery,Events,Unobtrusive Javascript,委派事件方法(第二个代码示例)只将事件处理程序附加到一个元素tbody,事件只需要向上冒泡一个级别(从单击的tr到tbody) 注意:委派事件不适用于。这是一个纯JavaScript解决方案,没有任何库或插件: document.addEventListener('click', function (e) { if (hasClass(e.target, 'bu')) { // .bu clicked // Do your thing } else

委派事件方法(第二个代码示例)只将事件处理程序附加到一个元素
tbody
,事件只需要向上冒泡一个级别(从单击的
tr
tbody


注意:委派事件不适用于。

这是一个纯JavaScript解决方案,没有任何库或插件:

document.addEventListener('click', function (e) {
    if (hasClass(e.target, 'bu')) {
        // .bu clicked
        // Do your thing
    } else if (hasClass(e.target, 'test')) {
        // .test clicked
        // Do your other thing
    }
}, false);
其中
hasClass

function hasClass(elem, className) {
    return elem.className.split(' ').indexOf(className) > -1;
}

这归功于戴夫和西姆·维达斯

使用更现代的JS,
hasClass
可以实现为:

function hasClass(elem, className) {
    return elem.classList.contains(className);
}

另一个解决方案是在创建元素时添加侦听器。在创建元素时,您将侦听器放入元素中,而不是将其放入主体中:

var myElement = $('<button/>', {
    text: 'Go to Google!'
});

myElement.bind( 'click', goToGoogle);
myElement.append('body');


function goToGoogle(event){
    window.location.replace("http://www.google.com");
}
var myElement=$(“”{
文字:“转到谷歌!”
});
绑定('click',gotogogle);
myElement.append('body');
函数goToGoogle(事件){
window.location.replace(“http://www.google.com");
}

我更喜欢使用选择器,并将其应用于文档

这将在文档上绑定自身,并将适用于页面加载后呈现的元素

例如:

$(document).on("click", 'selector', function() {
    // Your code here
});

绑定事件时不存在的任何p,如果您的页面是使用类名按钮动态创建元素,则将事件绑定到已存在的父级

$(文档).ready(函数(){
//特定家长点击
$(“.buttons”)。在(“单击”,“按钮”,函数()上){
警报(“点击”);
});  
//按钮类上的动态事件绑定
$(文档)。在(“单击”、“.button”,函数()上){
警报(“动态点击”);
});
$(“输入”).addClass(“按钮”);
});

2.
3.
6
动态创建元素上的事件绑定 单个元素:

$(document.body).on('click','.element', function(e) {  });
 $(document.body).on('click','.element *', function(e) {  });
子元素:

$(document.body).on('click','.element', function(e) {  });
 $(document.body).on('click','.element *', function(e) {  });
请注意添加的
*
。将为该元素的所有子元素触发一个事件

我注意到:

$(document.body).on('click','.#element_id > element', function(e) {  });
它不再起作用了,但它以前起过作用。我一直在使用谷歌的jQuery,但我不知道他们是否改变了它。

注意元素所在的“MAIN”类,例如

<div class="container">
     <ul class="select">
         <li> First</li>
         <li>Second</li>
    </ul>
</div>
试着这样做-

$(document).on( 'click', '.click-activity', function () { ... });
你可以用

$('.buttons').on('click', 'button', function(){
    // your magic goes here
});

这两种方法是等效的,但参数顺序不同

请参阅:

使用jQuery的
.on()
方法将事件处理程序附加到活动元素


同样从1.9版开始,
.live()
方法被删除。

当使用动态创建时,您可以将事件附加到元素

从jQuery 1.8开始,任何jQuery实例方法(jQuery.fn的方法)都可以用作传递给 第二个参数:

函数handleDynamicElementEvent(事件){
console.log(event.type,this.value)
}
//创建事件并将其附加到动态元素
jQuery(“”{
html:$.map(数组(3),函数(\ux,索引){
返回新选项(索引,索引)
}),
关于:{
更改:handleDynamicElementEvent
}
})
.附于(“主体”)

另一个创建元素和绑定事件的灵活解决方案()

//创建动态元素(container div)
var$div=$(“”,{id:'myid1',class:'myclass'});
//创建动态按钮
var$btn=$(“”,{type:'button',text:'Click me',class:'btn'});
//约束事件
$btn.click(函数(){//for mouseover-->$btn.on('mouseover',函数(){
console.log('clicked');
});
//将动态按钮附加到动态容器
$div.append($btn);
//将动态创建的元素添加到静态元素
$(“#框”)。追加($div);

注意:这将为每个元素创建一个事件处理程序实例(在循环中使用时可能会影响性能)

以下是动态创建的元素不响应单击的原因:

var body=$(“body”);
var BTN=$(“按钮”);
var btnB=$(“B”);
//文件中还没有“B”。
//因此,“$”(“button”)给出了“[A]”。
//只有'A'获得单击侦听器。
btns.on(“点击”,功能(){
console.log(this);
});
//对'B'来说太晚了。。。
body.append(btnB);

A

HTML文档
你好,世界
jQuery(文档).ready(函数($){
$(文档).on('mouseover','#hover id',function(){
$(this.css('color','yellowgreen');
});
$(文档).on('mouseout','#hover id',function(){
$(this.css('color','black');
});
});

我正在寻找一种解决方案,使
$.bind
$.unbind
在动态添加的元素中工作时不会出现问题

As采用了附加事件的技巧,以便在我访问的对象上创建一个假解绑:

const sendAction = function(e){ ... }
// bind the click
$('body').on('click', 'button.send', sendAction );

// unbind the click
$('body').on('click', 'button.send', function(){} );

将事件绑定到已存在的父级:

$(document).on("click", "selector", function() {
    // Your code here
});

我更喜欢以模块化功能的方式部署事件侦听器,而不是编写
文档
级别的事件侦听器脚本。因此,我喜欢下面的内容。注意,不能用同一个事件侦听器过度订阅元素,所以不必担心多次附加侦听器-只会有一个

var迭代次数=4;
var按钮;
var body=document.querySelector(“body”);
对于(var i=0;i
这是由事件委派完成的
var myElement = $('<button/>', {
    text: 'Go to Google!'
});

myElement.bind( 'click', goToGoogle);
myElement.append('body');


function goToGoogle(event){
    window.location.replace("http://www.google.com");
}
$(document).on("click", 'selector', function() {
    // Your code here
});
$(document.body).on('click','.element', function(e) {  });
 $(document.body).on('click','.element *', function(e) {  });
$(document.body).on('click','.#element_id > element', function(e) {  });
<div class="container">
     <ul class="select">
         <li> First</li>
         <li>Second</li>
    </ul>
</div>
$(document).ready(function(e) {
    $('.container').on( 'click',".select", function(e) {
        alert("CLICKED");
    });
 });
$(document).on( 'click', '.click-activity', function () { ... });
$('.buttons').on('click', 'button', function(){
    // your magic goes here
});
$('.buttons').delegate('button', 'click', function() {
    // your magic goes here
});
// creating a dynamic element (container div)
var $div = $("<div>", {id: 'myid1', class: 'myclass'});

//creating a dynamic button
 var $btn = $("<button>", { type: 'button', text: 'Click me', class: 'btn' });

// binding the event
 $btn.click(function () { //for mouseover--> $btn.on('mouseover', function () {
    console.log('clicked');
 });

// append dynamic button to the dynamic container
$div.append($btn);

// add the dynamically created element(s) to a static element
$("#box").append($div);
<html>
    <head>
        <title>HTML Document</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    </head>

    <body>
        <div id="hover-id">
            Hello World
        </div>

        <script>
            jQuery(document).ready(function($){
                $(document).on('mouseover', '#hover-id', function(){
                    $(this).css('color','yellowgreen');
                });

                $(document).on('mouseout', '#hover-id', function(){
                    $(this).css('color','black');
                });
            });
        </script>
    </body>
</html>
const sendAction = function(e){ ... }
// bind the click
$('body').on('click', 'button.send', sendAction );

// unbind the click
$('body').on('click', 'button.send', function(){} );
$(document).on("click", "selector", function() {
    // Your code here
});
$('.wrapper-class').on("click", '.selector-class', function() {
    // Your code here
});
<div class="wrapper-class">
    <button class="selector-class">
      Click Me!
    </button>
</div>