【问题标题】:How to access an input element by a non-standard attribute?如何通过非标准属性访问输入元素?
【发布时间】:2019-10-10 23:16:56
【问题描述】:

我有几个输入字段,其中名称和 id 属性会根据推出的服务器而变化,并且 class 也不是唯一的。每个输入字段的唯一唯一属性是“roiname”。
如何使用 jQuery 以跨服务器的方式获取该字段的值?

<input roiname="smallLocations" name="__field_13102" id="e5634b55-d6cc-4b32-a5aa-2120b4845dbb" type="number" class="form-control FormTextbox__Input" placeholder="4" value="" min="0" step="1" data-f-datainput="">

我尝试过这样的事情:

var smallLocations = $(":input").attr("smallLocations").val();

但这没有用。

【问题讨论】:

  • $('*[roiname]')[0].val();

标签: jquery forms jquery-selectors


【解决方案1】:

您当前的逻辑不起作用,因为您使用的是attr(),它检索属性的值,它没有找到该属性的元素。

要解决此问题,您需要使用属性选择器:

var roiname = $(':input[roiname]').val();
console.log(roiname);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input roiname="smallLocations" value="123" name="__field_13102" id="e5634b55-d6cc-4b32-a5aa-2120b4845dbb" type="number" class="form-control FormTextbox__Input" placeholder="4" value="" min="0" step="1" data-f-datainput="">

【讨论】:

  • 我认为标签名称前的冒号是错字。
  • 嗯,很有趣。感谢您的提示:) 虽然我猜这不是 cmets 部分的地方。
【解决方案2】:

您不是在寻找 属性 的值,而是在寻找 输入 的值。 (另外,您的input 没有一个名为“smallLocations”的属性,这是其中一个属性的值。)

类似这样的:

$('input[roiname="smallLocations"]').val()

【讨论】:

    【解决方案3】:

    使用嘶嘶声有属性选择器

    var smallLocations = $("input[roiname]").val();

    文档在这里

    https://api.jquery.com/has-attribute-selector/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      • 2012-07-05
      • 2018-02-02
      相关资源
      最近更新 更多