Jquery - 检查单选按钮,获取特定标签内容

Jquery - Check Radio Button, Get Specific Label Content

在过去的几天里,我花了好几个小时尝试了几乎所有我能找到的 Stack Overflow 片段,自己将其整合在一起,但没有任何东西能按我需要的方式工作。在这个阶段,我希望你们中的一个能好心地帮助我。

Objective:

我在订单表单上显示了一个单选按钮列表。我只想从选中的单选输入中提取特定标签内容并将其保存到变量,即“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 Fiddle: http://jsfiddle.net/1t1edf8v/5/

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

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

简单地说,使用querySelector:

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

已更新 fiddle: http://jsfiddle.net/1t1edf8v/3/

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

要仅提取字符串“3 product name”或任何其他字符串,您可以使用拆分函数或 regEx。这里你只需要一些模式。

例如,

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

已更新 fiddle: http://jsfiddle.net/1t1edf8v/8/

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

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

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

id 属性更改为唯一,并将 <label> 元素的 for 属性更改为将给定的 <label> 与正确的 <input>, 以下成为可能:

// 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.

当然,用plain JavaScript/the 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.

参考文献: