【问题标题】:get span children of a radio button element获取单选按钮元素的跨度子元素
【发布时间】:2015-03-06 14:02:00
【问题描述】:

我有一排用于支付运费的单选按钮。如果用户单击按钮,我需要收集单选按钮元素使用的 div 中包含的两个跨度(价格和成本)。所有单选按钮共享同一个名为“所有项目”的类这是 html:

<li class="all-items">
<input name="shipping_method" type="radio" value="usps_1" id="s_method_usps_1" checked="checked" class="radio">
<label for="s_method_usps_1" style="display:block; overflow:hidden;">
<span class="price">$30.20</span>
<span class="cost">Priority Mail </span>
</label>
</li>

这是我正在使用的 jQuery。

         jQuery("input:radio[name=shipping_method]").click(function() {
         var shipping = jQuery(this).val();
         console.log(shipping);
         console.log(jQuery(this).find('span'));
         });

【问题讨论】:

  • 仅供参考,可能是错误的标题,但由于input 是无效元素,它不能包含任何内容。在这里你要使用:jQuery(this).next('label').find('span')。或者更好:jQuery(this).closest('.all-items').find('.price, .cost')
  • 嗨狼,你介意把它放在答案中,我会接受吗?效果很好!
  • 请参阅"Should questions include “tags” in their titles?",其中的共识是“不,他们不应该”!

标签: javascript jquery html


【解决方案1】:

SPAN 不是 radio 元素的子元素。我建议您获取相关的 LI 父级,然后定位相关的 SPAN,例如:

jQuery(this).closest('.all-items').find('.price, .cost') // add specific SPAN classes if needed

我个人更喜欢它而不是 jQuery(this).closest('.all-items').find('span'),因为它明确地告诉您正在寻找哪些特定的 SPAN。

【讨论】:

    猜你喜欢
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    相关资源
    最近更新 更多