简体   繁体   English

如何使用函数更改jQuery ID选择器

[英]How to change the jQuery ID selector with a function

In my html file I have #book1 #book2 etc. as divs. 在我的html文件中,我将#book1#book2等作为div。

I'm trying to set it up so that I can call the function (addToPage) for each product and pass in my object (book1) and it will put my product info onto the page. 我正在尝试对其进行设置,以便可以为每个产品调用函数(addToPage)并传入我的对象(book1),它将把我的产品信息放到页面上。 Any help is appreciated! 任何帮助表示赞赏!

var book1 = {
name:'name of book', 
author:'name of author'
}

//////////// THIS WORKS

function addToPage(productId) {
$('#book1 .name').text(productId.name);
$('#book1 .author').text(productId.author);
}
addToPage(book1)

/////////// THIS DOESN'T WORK / CAN YOU TELL ME WHY?

function addToPage(productId) {
$('#productId .name').text(productId.name);
$('#productId .author').text(productId.author);
}
addToPage(book1)

You are passing in an object. 您正在传递一个对象。 So the variable will not be available as part of the argument. 因此,该变量将无法用作参数的一部分。

Use 采用

 var book1 = { id: 'book1', name: 'name of book', author: 'name of author' } function addToPage(product) { $('#' + product.id + ' .name').text(product.name); $('#' + product.id + ' .author').text(product.author); } addToPage(book1) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="book1"> <p class="name"></p> <p class="author"></p> </div> 

I believe you have the elements book1 and book2 etc in you HTML. 我相信您的HTML中包含book1book2等元素。 But you jQuery selector is looking for an element by id productId . 但是您的jQuery选择器正在通过id productId查找元素。 You need to replace that with the variable that you are passing in so that you are making the right selection. 您需要用传入的变量替换它,以便进行正确的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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