简体   繁体   中英

How to pass in parameters by their id?

This might be a silly question, because I have not found any information on my specific problem anywhere, and this is my first javascript/html project.

I want to pass in the name of a book, and its price, by the id's associated them (book1 and price1). My thinking is that this way, if the name or price changes later, the function "addToCart(book1,price1)" will automatically pass in the updated name/price. Is it possible to pass strings into a function this way in javascript/html5?

Here is part of the code:

<td>
    <span class="bookName" id="book1">
        <b>Artificial Intelligence: Modern Approach</b>
    </span> <br>
    <b>PRICE: $</b> 
    <span id="price1"> 158.55 </span> 
    <button type="button" onclick="addToCart(book1, price1)">Add to cart!</button>
</td>

Thanks in advance!

HTML

<button type="button" onclick="addToCart('book1', 'price1')">Add to cart!</button>

JS

function addToCart(productId, priceId) {
    // ...
}

Just a few other notes about your code:

  • Use <br /> instead of <br> , otherwise it is not valid HTML
  • Ideally use a <label> tag, this makes it more accessible

Eg

<label for="price1">PRICE:</label>
<span>$</span>
<span id="price1">158.55</span>
  • It's normally better to hook up events in a separate JavaScript file (or <script> tag) instead of HTML attributes. This provides a more clean separation of your functionality and your markup/UI

assuming you're using jquery:

onClick="addToCart($(this).siblings('.bookName').text(), $(this).siblings('.price').text())"

This would require you to put a class onto the price span ( <span class="price">158.55</span> ).

Remember... every element in the DOM "knows" where it is, and you can trivially navigate up/down this tree to find related elements nearby.

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