0

我有一个使用类和 id 的情况,但我需要在 jQuery 中传递一个变量。你怎么推荐?

HTML

<input
    type="text"
    id="cannot_change_this"
    class="rather_not_append_extra_classes_just_for_a_variable"
    value="Full Text Name"
    hash="ABCDE">

通过自动完成选择每个值时,都有一个关联的哈希值。在上面的示例中,值可能是Full Text Name,但这不是唯一的。我真正需要传递的是 hash: ABCDE

我无法更改 id,我宁愿不添加额外的类,并且必须过滤掉用于样式的类以获取我的哈希值。而且由于它是一个input我也不能使用 .text() 。

我还能如何将ABCDE哈希传递给 jQuery?

4

4 回答 4

2

看看使用jQuery的数据方法

http://api.jquery.com/jQuery.data/

您可以在 javascript 中计算值的哈希值,然后将其设置为输入的数据。

此外,如果使用 HTML5,您可以在 HTML 中专门声明数据属性。所以你可以使用一个属性data-hash=HASH来设置你的数据。

或者,如果您不关心合规性或者您没有使用 HTML5,您可以设置自己的属性,例如

<input type="text" id="cannot_change_this"
class="rather_not_append_extra_classes_just_for_a_variable" 
value="Full Text Name" hash="ABCDE" />

像这样用 jQuery 阅读它:

var hash = $('input#idOfInput').attr('hash');
于 2012-08-10T18:26:41.047 回答
1

如果我做对了。

设置值:

$("#cannot_change_this").data("hash", hashValue);

稍后获取值:

$("#cannot_change_this").data("hash");
于 2012-08-10T18:27:28.283 回答
1

您可以只使用 title 属性:

<input type="text" id="cannot_change_this"
class="rather_not_append_extra_classes_just_for_a_variable" 
value="Full Text Name"title="ABCDE" />

它是所有输入的标准属性。

于 2012-08-10T18:32:01.500 回答
0

你可以有类似的东西:

jQuery(document).ready(function(){
//SET:
 jQuery("#cannot_change_this").attr("new-value", "ABCDE");
//READ:
 var val = jQuery("#cannot_change_this").attr("new-value");
 alert(val);
 });
于 2012-08-10T18:32:38.630 回答