简体   繁体   中英

Passing a variable into a function in jQuery doesn't work

I'm just curious why this doesn't work. If I pass the name 'book1' directly it works, but if I pass it through the function's parameter it doesn't.

Any help would be appreciated. Thanks.

var add_to_page = function(item) {
    $('#item .name').text(item.name)
    //$('#book1 .name').text(book1.name) //<--- this works!!

};

add_to_page('book1');

Supposing book1 is an object, your mistake is that you are passing a string to add_to_page() . Try replacing

add_to_page('book1');

with

add_to_page(book1);

EDIT

The selector is wrong too. It should be obvious that $("#item .name") is not the same as $("#book .name") . What you seem to be trying to achieve cannot be accomplished, because you are trying to use one single argument ( item ) as a string in one place and as an object in another one.

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