简体   繁体   English

如何通过ID传递参数?

[英]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. 这可能是一个愚蠢的问题,因为我在任何地方都没有找到关于特定问题的任何信息,这是我的第一个javascript / html项目。

I want to pass in the name of a book, and its price, by the id's associated them (book1 and price1). 我想通过ID关联的书(book1和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. 我的想法是,这样,如果以后更改名称或价格,函数“ addToCart(book1,price1)”将自动传递更新后的名称/价格。 Is it possible to pass strings into a function this way in javascript/html5? 是否可以在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 的HTML

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

JS JS

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

Just a few other notes about your code: 关于您的代码的其他一些注意事项:

  • Use <br /> instead of <br> , otherwise it is not valid HTML 使用<br />代替<br> ,否则它是无效的HTML
  • Ideally use a <label> tag, this makes it more accessible 理想情况下,使用<label>标签,这将使其更易于访问

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. 通常最好将事件挂接到单独的JavaScript文件(或<script>标记)中,而不是HTML属性中。 This provides a more clean separation of your functionality and your markup/UI 这样可以更清晰地分离您的功能和标记/ UI

assuming you're using jquery: 假设您使用的是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> ). 这将需要您在价格范围内放置一个类( <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. 记住... DOM中的每个元素都“知道”它的位置,您可以在该树中向上/向下导航以查找附近的相关元素。

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

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