【问题标题】:Jquery - Check Radio Button, Get Specific Label ContentJquery - 检查单选按钮,获取特定标签内容
【发布时间】:2017-09-27 11:18:26
【问题描述】:

在过去的几天里,我花了好几个小时尝试几乎所有我能找到的 Stack Overflow sn-p 来自己破解它,但没有任何东西能按我需要的方式工作。在这个阶段,我希望你们中的一个人能帮助我。

目标:

我有一个显示在订单表单上的单选按钮列表。我只想从选中的单选输入中提取特定标签内容并将其保存到变量中,即“3 产品名称”或“1 产品名称”。

$("input:radio").click(function() {
  var label_description = this.parentElement.outerText;
  alert(label_description);
});

//Goal- Extract specific label content from checked radio input e.g "3 Product Name" or "1 Product Name"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pull-left elOrderProductOptinProductName">
  <input type="radio" id="lbl-01" name="purchase[product_id]" value="12374747">
  <div class="pull-right elOrderProductOptinPrice" data-cf-product-price="true" taxamo-currency="USD">$X.XX</div>
  <label for="lbl-01" data-cf-product-name="true">3 Product Name - Text here</label>
</div>

<div class="pull-left elOrderProductOptinProductName">
  <input type="radio" id="lbl-01" name="purchase[product_id]" value="839909">
  <div class="pull-right elOrderProductOptinPrice" data-cf-product-price="true" taxamo-currency="USD">$X.XX</div>
  <label for="lbl-01" data-cf-product-name="true">4 Product Name - Text here</label>
</div>

<div class="pull-left elOrderProductOptinProductName">
  <input type="radio" id="lbl-01" name="purchase[product_id]" value="839909">
  <div class="pull-right elOrderProductOptinPrice" data-cf-product-price="true" taxamo-currency="USD">$X.XX</div>
  <label for="lbl-01" data-cf-product-name="true">6 Product Name - Text here</label>
</div>

<div class="pull-left elOrderProductOptinProductName">
  <input type="radio" id="lbl-01" name="purchase[product_id]" value="839909">
  <div class="pull-right elOrderProductOptinPrice" data-cf-product-price="true" taxamo-currency="USD">$X.XX</div>
  <label for="lbl-01" data-cf-product-name="true">1 Product Name</label>
</div>

JS 小提琴:http://jsfiddle.net/1t1edf8v/5/

如您所见,我所拥有的只是提取完整标签内容和价格的工作代码。我明白为什么会发生这种情况,我只是无法隔离我需要的东西。

非常感谢您对此的任何帮助!

【问题讨论】:

  • 你的意思是,你不想在点击广播 btn 后看到整个文本?
  • 正确,现在它会提取价格和完整标签。我只想要标签中的特定内容,例如 Radio 1 检查警报“3 Product Name”
  • 请在以后将您的 (minimal reproducible example) 代码放入您的问题中,这样用户就不必访问外部网站来查看您的 HTML 以了解您的 JavaScript 正在做什么.
  • 感谢大卫的提醒,会做的。

标签: jquery label radio


【解决方案1】:

简单地说,使用 querySelector:

 alert(this.parentElement.querySelector("[data-cf-product-name]").outerText)

更新的小提琴: http://jsfiddle.net/1t1edf8v/3/

请注意,我在 querySelector 函数中使用 属性选择器,如果您愿意,可以使用其他选择器。

要提取字符串“3 产品名称”或任何其他字符串,您可以使用拆分函数或正则表达式。你只需要一些模式。

例如,

var text = this.parentElement.querySelector("[data-cf-product-name]").outerText;
var selected = (text.split("-"))[0].trim();
alert(selected);

更新的小提琴: http://jsfiddle.net/1t1edf8v/8/

【讨论】:

  • 感谢 Nitesh,这仅隔离了标签内容,这很好。但是,我需要从该标签中提取特定内容。想法?
  • 举个例子,你想拔出什么……我会尽力帮忙的
  • 示例:如果选中 Radio 1 - 拉出“3 产品名称”,如果选中 Radio 2 - 拉出“4 Product Name”,如果选中 Radio 3 - 拉出“6 Product Name”,如果选中 Radio 4 - 拉出“1 个产品名称”
  • 太好了,非常感谢您的帮助 Nitesh!你不会相信我自己花了多少时间尝试这样做!
  • 再次打开此代码,因为此代码在 Firefox 中不起作用。花了一段时间来确定这是问题代码,果然 JSFiddle 在 FF 中不起作用。
【解决方案2】:

试试这个 $(this).siblings('label').HTML()

但更好的方法是为您的 div 或标签分配一些 id,以便您以后区分它。

【讨论】:

    【解决方案3】:

    您发布的代码有两个问题;您的 HTML 重复了许多具有相同 id 的元素:这是无效的,因为 id 必须唯一标识文档中的一个元素(如果您想共享一个公共标识符,请使用类名或自定义data-* 属性)。共享id 属性的结果意味着&lt;label&gt; 元素在单击时只能选择具有该特定id 的第一个元素(一个&lt;input&gt; 元素与多个&lt;label&gt; 关联是完全有效的元素)。

    id 属性更改为唯一,并将&lt;label&gt; 元素的for 属性更改为将给定&lt;label&gt; 与正确的&lt;input&gt; 相关联,以下成为可能:

    // using attribute-selection to identify the <input> elements
    // whose 'type' attribute is equal to 'radio', and binding the
    // anonymous function of the on() method as the event-handler
    // for the 'change' event:
    $('input[type=radio]').on('change', function() {
    
      // using the 'let' statement to create the variable
      // 'productName,' and finding the first <label> element
      // associated with the changed radio-element, retrieving
      // the textContent of that <label> and splitting that
      // text on the '-' character:
      let productName = this.labels[0].textContent.split('-');
    
      // if we have a truthy productName variable:
      if (productName) {
        // we retrieve the first part of the Array returned
        // by String.prototype.split(), trim that text to
        // remove leading and trailing white-space and then
        // log it to the console:
        console.log(productName[0].trim());
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="pull-left elOrderProductOptinProductName">
      <input type="radio" id="lbl-01" name="purchase[product_id]" value="12374747">
      <div class="pull-right elOrderProductOptinPrice" data-cf-product-price="true" taxamo-currency="USD">$X.XX</div>
      <label for="lbl-01" data-cf-product-name="true">3 Product Name - Text here</label>
    </div>
    
    <div class="pull-left elOrderProductOptinProductName">
      <input type="radio" id="lbl-02" name="purchase[product_id]" value="839909">
      <div class="pull-right elOrderProductOptinPrice" data-cf-product-price="true" taxamo-currency="USD">$X.XX</div>
      <label for="lbl-02" data-cf-product-name="true">4 Product Name - Text here</label>
    </div>
    
    <div class="pull-left elOrderProductOptinProductName">
      <input type="radio" id="lbl-03" name="purchase[product_id]" value="839909">
      <div class="pull-right elOrderProductOptinPrice" data-cf-product-price="true" taxamo-currency="USD">$X.XX</div>
      <label for="lbl-03" data-cf-product-name="true">6 Product Name - Text here</label>
    </div>
    
    <div class="pull-left elOrderProductOptinProductName">
      <input type="radio" id="lbl-04" name="purchase[product_id]" value="839909">
      <div class="pull-right elOrderProductOptinPrice" data-cf-product-price="true" taxamo-currency="USD">$X.XX</div>
      <label for="lbl-04" data-cf-product-name="true">1 Product Name</label>
    </div>

    JS Fiddle demo.

    当然,使用纯 JavaScript/DOM API,上面的也是完全可能的:

    function retrieveLabelText() {
    
      // 'this' is passed from EventTarget.addEventListener(),
      // here we again retrieve the first <label> element
      // associated with the changed <input> element,
      // retrieve the textContent of that element and then
      // split the String into an Array using
      // String.prototype.split():
      let text = this.labels[0].textContent.split('-');
    
      // if we have a truthy 'text' value:
      if (text) {
    
        // we trim the first element of the Array of
        // Strings, and log that trimmed String to the
        // console:
        console.log(text[0].trim());
      }
    }
    
    // here we retrieve all elements in the document that match
    // CSS selector, which searches for all <input> elements
    // whose 'type' is equal to 'radio', the returned NodeList
    // is passed to Array.from(), which converts the Array-like
    // NodeList into an Array, with access to the Array methods:
    let = radios = Array.from(document.querySelectorAll('input[type=radio]'));
    
    // here we iterate over the Array of <input> elements using
    // Array.prototype.forEach():
    radios.forEach(
    
      // 'radio' is the current radio <input> element of the
      // Array of elements over which we're iterating,
      // here we use an Arrow function to add an event-listener
      // to the current <input> element, using the
      // EventTarget.addEventListener() method to bind the named
      // function ('retrieveLabelText') as the event-handler
      // for the 'change' event:
      radio => radio.addEventListener('change', retrieveLabelText)
    );
    <div class="pull-left elOrderProductOptinProductName">
      <input type="radio" id="lbl-01" name="purchase[product_id]" value="12374747">
      <div class="pull-right elOrderProductOptinPrice" data-cf-product-price="true" taxamo-currency="USD">$X.XX</div>
      <label for="lbl-01" data-cf-product-name="true">3 Product Name - Text here</label>
    </div>
    
    <div class="pull-left elOrderProductOptinProductName">
      <input type="radio" id="lbl-02" name="purchase[product_id]" value="839909">
      <div class="pull-right elOrderProductOptinPrice" data-cf-product-price="true" taxamo-currency="USD">$X.XX</div>
      <label for="lbl-02" data-cf-product-name="true">4 Product Name - Text here</label>
    </div>
    
    <div class="pull-left elOrderProductOptinProductName">
      <input type="radio" id="lbl-03" name="purchase[product_id]" value="839909">
      <div class="pull-right elOrderProductOptinPrice" data-cf-product-price="true" taxamo-currency="USD">$X.XX</div>
      <label for="lbl-03" data-cf-product-name="true">6 Product Name - Text here</label>
    </div>
    
    <div class="pull-left elOrderProductOptinProductName">
      <input type="radio" id="lbl-04" name="purchase[product_id]" value="839909">
      <div class="pull-right elOrderProductOptinPrice" data-cf-product-price="true" taxamo-currency="USD">$X.XX</div>
      <label for="lbl-04" data-cf-product-name="true">1 Product Name</label>
    </div>

    JS Fiddle demo.

    参考资料:

    【讨论】:

    • 嗨,David,感谢您抽出宝贵时间撰写如此详细的有用回复。在这里学到了很多!不幸的是,我受制于此页面上的代码,只能使用 Jquery 对其进行操作。我重新打开了这个问题,因为之前接受的答案在 Firefox 上不起作用。搜索继续。
    猜你喜欢
    • 2013-02-05
    • 1970-01-01
    • 2012-02-11
    • 2013-07-15
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    相关资源
    最近更新 更多