Py学习  »  Jquery

jquery函数不使用Ajax返回/呈现的页面[重复]

gamernes konge • 5 年前 • 2233 次点击  

我有一些代码,我在其中循环浏览页面上的所有选择框并绑定 .hover 事件让他们在宽度上做点小动作 mouse on/off .

这在页面上发生,并且工作得很好。

我遇到的问题是,在初始循环之后,通过Ajax或DOM添加的任何选择框都不会绑定事件。

我找到了这个插件( jQuery Live Query Plugin 但是,在我用插件为页面添加另一个5K之前,我想看看是否有人知道这样做的方法,可以直接使用jquery,也可以使用其他选项。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38189
 
2233 次点击  
文章 [ 23 ]  |  最新文章 5 年前
Evhz
Reply   •   1 楼
Evhz    7 年前

我在寻找解决办法 $.bind $.unbind 在动态添加的元素中无问题地工作。

AS on() 使用附加事件的技巧,以便在我遇到的事件上创建一个假的解除绑定:

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

// unbind the click
$('body').on('click', 'button.send', function(){} );
Fakhrul Hasan
Reply   •   2 楼
Fakhrul Hasan    7 年前
<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>
Prasad De Silva
Reply   •   3 楼
Prasad De Silva    6 年前

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

// 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);

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

Ron Royston
Reply   •   4 楼
Ron Royston    7 年前

我更喜欢以模块化的函数方式部署事件侦听器,而不是编写 document 级别事件侦听器。所以,我喜欢下面。 注意,不能用同一个事件侦听器超额订阅一个元素,因此不要担心多次附加一个侦听器-只有一个链接。

var iterations = 4;
var button;
var body = document.querySelector("body");

for (var i = 0; i < iterations; i++) {
    button = document.createElement("button");
    button.classList.add("my-button");
    button.appendChild(document.createTextNode(i));
    button.addEventListener("click", myButtonWasClicked);
    body.appendChild(button);
}

function myButtonWasClicked(e) {
    console.log(e.target); //access to this specific button
}
truongnm
Reply   •   5 楼
truongnm    7 年前

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

$(document).on("click", "selector", function() {
    // Your code here
});
Kalpesh Patel
Reply   •   6 楼
Kalpesh Patel    8 年前

使用 .on() jquery方法 http://api.jquery.com/on/ 将事件处理程序附加到活动元素。

从1.9版起 .live() 方法已删除。

Rohit Suthar
Reply   •   7 楼
Rohit Suthar    9 年前

像这样试试-

$(document).on( 'click', '.click-activity', function () { ... });
Asif J
Reply   •   8 楼
Asif J    6 年前

这是由事件委托完成的 . 事件将绑定到包装类元素,但将委托给选择器类元素。这就是它的工作原理。

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

注:

包装类元素可以是任何东西,例如文档、主体或包装器。 包装应该已经存在 . 然而, selector 不一定需要在页面加载时出现。它可能稍后发生,事件将绑定到 选择器 没有失败 .

Ankit Kathiriya
Reply   •   9 楼
Ankit Kathiriya    9 年前

任何P 那不存在吗 在绑定事件时,如果您的页面是 动态创建元素 具有类名 按钮 将事件绑定到已存在的父级

$(document).ready(function(){
  //Particular Parent chield click
  $(".buttons").on("click","button",function(){
    alert("Clicked");
  });  
  
  //Dynamic event bind on button class  
  $(document).on("click",".button",function(){
    alert("Dymamic Clicked");
  });
  $("input").addClass("button");  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="buttons">
  <input type="button" value="1">
  <button>2</button>
  <input type="text">
  <button>3</button>  
  <input type="button" value="5">  
  </div>
<button>6</button>
leaf
Reply   •   10 楼
leaf    7 年前

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

var body = $("body");
var btns = $("button");
var btnB = $("<button>B</button>");
// `<button>B</button>` is not yet in the document.
// Thus, `$("button")` gives `[<button>A</button>]`.
// Only `<button>A</button>` gets a click listener.
btns.on("click", function () {
  console.log(this);
});
// Too late for `<button>B</button>`...
body.append(btnB);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>

作为解决方法,您必须倾听所有单击并检查源元素:

var body = $("body");
var btnB = $("<button>B</button>");
var btnC = $("<button>C</button>");
// Listen to all clicks and
// check if the source element
// is a `<button></button>`.
body.on("click", function (ev) {
  if ($(ev.target).is("button")) {
    console.log(ev.target);
  }
});
// Now you can add any number
// of `<button></button>`.
body.append(btnB);
body.append(btnC);
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js”></script>
<button>A</button>

这被称为“事件授权”。好消息,这是jquery中内置的特性:-)

var i = 11;
var body = $("body");
body.on("click", "button", function () {
  var letter = (i++).toString(36).toUpperCase();
  body.append($("<button>" + letter + "</button>"));
});
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js”></script>
<button>A</button>
Mensur Grišević
Reply   •   11 楼
Mensur Grišević    8 年前

你可以用

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

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

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

见: jQuery Delegate Event

Milan Chheda guest271314
Reply   •   12 楼
Milan Chheda guest271314    7 年前

当使用 jQuery(html, attributes) .

自jquery 1.8起 ,任何jquery实例方法(方法 jQuery.fn )可以用作传递给的对象的属性 第二个参数:

function handleDynamicElementEvent(event) {
  console.log(event.type, this.value)
}
// create and attach event to dynamic element
jQuery("<select>", {
    html: $.map(Array(3), function(_, index) {
      return new Option(index, index)
    }),
    on: {
      change: handleDynamicElementEvent
    }
  })
  .appendTo("body");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
Peter Mortensen edosoft
Reply   •   13 楼
Peter Mortensen edosoft    9 年前

注意“main”类,例如,元素被放置在

<div class="container">
     <ul class="select">
         <li> First</li>
         <li>Second</li>
    </ul>
</div>

在上述场景中,jquery将监视的主要对象是“container”。

然后在容器下基本上有元素名,比如 ul , li select :

$(document).ready(function(e) {
    $('.container').on( 'click',".select", function(e) {
        alert("CLICKED");
    });
 });
Matt C Vatsal
Reply   •   14 楼
Matt C Vatsal    7 年前

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

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

例如:

$(document).on("click", $(selector), function() {
    // Your code here
});
Peter Mortensen edosoft
Reply   •   15 楼
Peter Mortensen edosoft    9 年前

另一种解决方案是在创建元素时添加侦听器。不是把监听器放在主体中,而是把监听器放在创建元素的那一刻:

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

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


function goToGoogle(event){
    window.location.replace("http://www.google.com");
}
Peter Mortensen edosoft
Reply   •   16 楼
Peter Mortensen edosoft    9 年前

动态创建元素上的事件绑定

单一元素:

$(document.body).on('click','.element', function(e) {  });

子元素:

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

注意添加的 * . 将为该元素的所有子元素触发一个事件。

我注意到:

$(document.body).on('click','.#element_id > element', function(e) {  });

它已经不起作用了,但它以前也起作用了。我一直在使用谷歌的jquery CDN 但我不知道他们是否改变了。

Peter Mortensen edosoft
Reply   •   17 楼
Peter Mortensen edosoft    9 年前

您可以使用live()方法将元素(甚至是新创建的元素)绑定到事件和处理程序,如onclick事件。

下面是我编写的一个示例代码,在这里您可以看到live()方法如何将所选元素(甚至是新创建的元素)绑定到事件:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
    </head>

    <body>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js"></script>

        <input type="button" id="theButton" value="Click" />
        <script type="text/javascript">
            $(document).ready(function()
                {
                    $('.FOO').live("click", function (){alert("It Works!")});
                    var $dialog = $('<div></div>').html('<div id="container"><input type ="button" id="CUSTOM" value="click"/>This dialog will show every time!</div>').dialog({
                                                                                                         autoOpen: false,
                                                                                                         tite: 'Basic Dialog'
                                                                                                     });
                    $('#theButton').click(function()
                    {
                        $dialog.dialog('open');
                        return('false');
                    });
                    $('#CUSTOM').click(function(){
                        //$('#container').append('<input type="button" value="clickmee" class="FOO" /></br>');
                        var button = document.createElement("input");
                        button.setAttribute('class','FOO');
                        button.setAttribute('type','button');
                        button.setAttribute('value','CLICKMEE');
                        $('#container').append(button);
                    });
                    /* $('#FOO').click(function(){
                                                     alert("It Works!");
                                                 }); */
            });
        </script>
    </body>
</html>
Willi Mentzel
Reply   •   18 楼
Willi Mentzel    9 年前

尝试使用 .live() 而不是 .bind() ; .live()。 将绑定 .hover 在执行Ajax请求后,选中复选框。

Peter Mortensen edosoft
Reply   •   19 楼
Peter Mortensen edosoft    9 年前

您可以简单地将事件绑定调用包装到一个函数中,然后调用它两次:一次在文档就绪时调用,一次在添加新的DOM元素的事件之后调用。如果这样做,您将希望避免在现有元素上绑定同一事件两次,这样您就需要取消绑定现有事件,或者(更好)只绑定到新创建的DOM元素。代码如下所示:

function addCallbacks(eles){
    eles.hover(function(){alert("gotcha!")});
}

$(document).ready(function(){
    addCallbacks($(".myEles"))
});

// ... add elements ...
addCallbacks($(".myNewElements"))
Peter Mortensen edosoft
Reply   •   20 楼
Peter Mortensen edosoft    9 年前

创建对象时,可以将事件添加到对象中。如果您在不同的时间将相同的事件添加到多个对象中,那么创建一个命名函数可能是一种方法。

var mouseOverHandler = function() {
    // Do stuff
};
var mouseOutHandler = function () {
    // Do stuff
};

$(function() {
    // On the document load, apply to existing elements
    $('select').hover(mouseOverHandler, mouseOutHandler);
});

// This next part would be in the callback from your Ajax call
$("<select></select>")
    .append( /* Your <option>s */ )
    .hover(mouseOverHandler, mouseOutHandler)
    .appendTo( /* Wherever you need the select box */ )
;