【问题标题】:JQuery get value of elements selected by Attribute-Starts-With-SelectorJQuery 获取 Attribute-Starts-With-Selector 选择的元素的值
【发布时间】:2018-01-29 04:42:01
【问题描述】:

我正在尝试获取正则表达式选择的每个元素的每个值。

具体来说,我有一个这样的输入列表,由循环生成

 <input type="file" name="file[{$some_file.id}]">

我正在尝试像这样通过 jquery 获取每个输入的值

$("input[name^='file[']").change(function () {
  //get each input value
})

我尝试了this.val(),但显然它不起作用。非常感谢您的帮助。

【问题讨论】:

  • 看不到任何正则表达式。您似乎正在使用attribute-starts-with selector
  • 哦,是的,这就是我的意思,已编辑,抱歉没有使用精确的词:D。谢谢。

标签: javascript jquery jquery-selectors


【解决方案1】:

事件处理程序this 绑定是元素本身,而不是jQuery 对象。

来自.on()

当 jQuery 调用处理程序时,this 关键字是对传递事件的元素的引用

你想要的

this.value

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#Value

$('input[name^="file["]').on('change', function() {
  console.info(this.name, this.value)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="file[0]">
<input type="file" name="file[1]">
<input type="file" name="file[2]">
<input type="file" name="not-this-one">

或者,像这样将元素包装在jQuery 对象中并使用.val() 方法

$(this).val()

【讨论】:

  • 感谢您提供非常详细和有用的回答
猜你喜欢
  • 2013-09-02
  • 1970-01-01
  • 2012-03-02
  • 1970-01-01
  • 1970-01-01
  • 2014-12-09
  • 1970-01-01
  • 2016-11-30
  • 2014-09-19
相关资源
最近更新 更多