简体   繁体   中英

Click list element to slide up in jQuery

How do I delegate a click event to a list element that triggers it to slide up?

Here is my attempt:

http://jsfiddle.net/Sdh2G/

HTML

<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>

JS

$(document).delegate($("li"), "click", function() { $(this).slideUp(); console.log("click"); });

It throws the following error: Uncaught TypeError: Cannot use 'in' operator to search for 'display' in undefined

Using the .on() method is quite easy to delegate events:

http://jsfiddle.net/Sdh2G/1/

$(document).on("click","li", function() {
    $(this).slideUp();
    console.log("click");
});

http://api.jquery.com/on/

尝试:

$('li').click(function() {$(this).slideUp();});
$(document).delegate($("li"), "click", function()
                        ^----   Supposed to be a string and not a jQuery object

supposed to be

$(document).delegate("li", "click", function()

The selector argument should be of type String not a jQuery object . That is the cause of the error.

Also delegate is superseeded by on as of version 1.7.0

So replace that with

$(document).on("click", "li", function() {

Delegate Fiddle

On Fiddle

How about

$(document).on( "click", "li",function() { $(this).slideUp(); });

http://jsfiddle.net/Sdh2G/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM