如何使用jQuery更改输入字段中非HTML属性的值?

如何使用jQuery更改输入字段中非HTML属性的值?,jquery,attributes,Jquery,Attributes,我有一个如下所示的输入框: <input type="text" value="" somethingSpecial="filename.txt" id="myID" class="box"> <select name="type" class="form-select" id="type"> <option value="keyword" selected="selected" otherValue="filename.txt">Keyword&l

我有一个如下所示的输入框:

<input type="text" value="" somethingSpecial="filename.txt" id="myID" class="box">
<select name="type" class="form-select" id="type">
    <option value="keyword" selected="selected" otherValue="filename.txt">Keyword</option>
    <option value="title" otherValue="filename1.txt">Title</option>
    <option value="author" otherValue="filename2.txt">Author</option>
    <option value="subject" otherValue="filename3.txt">Subject</option>
</select>

我还有一个选择列表,如下所示:

<input type="text" value="" somethingSpecial="filename.txt" id="myID" class="box">
<select name="type" class="form-select" id="type">
    <option value="keyword" selected="selected" otherValue="filename.txt">Keyword</option>
    <option value="title" otherValue="filename1.txt">Title</option>
    <option value="author" otherValue="filename2.txt">Author</option>
    <option value="subject" otherValue="filename3.txt">Subject</option>
</select>

关键词
标题
作者
主题
当一个用户从这个选择列表中选择一个选项时,比如说,为了这个例子的缘故,“Title”,那么我需要将“otherValue”从这个字段中拉出,所以将“filename1.txt”替换为输入框中的“somethingSpecial”值

通常,我只需要使用一个函数来访问HTML属性,比如名称、id、类等等。。。但很明显,我使用的属性不是常规属性。

类似于:

$("#myid").attr("otherValue")

如果要执行这些操作,可以使用
.attr()
,但首选方法是使用自定义数据属性(其名称以
data-
开头)和
.data()
方法来访问/更改它们。它们是HTML5的一部分,但在HTML的早期版本中也可以访问(参见John Resig的文章:)

然后像这样改变:

jQuery('#myID').data('somethingSpecial')
jQuery('#myID').data('somethingSpecial', 'something else')

研究如何使用jquery.data()

您可以在标记中使用HTML5语法,如:

<option id="title" value="title" data-otherValue="filename1.txt">Title</option>

我相信您可以在这个示例的基础上选择数组或其他选项。

我应该补充的是,所有浏览器都支持jquery,即使是旧的IE6和不同于HTML5的doctype。