javascript jquery 获取自定义(编造)属性值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8087093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery get a custom (made up) Attribute value
提问by Ahoura Ghotbi
I have a the following html piece :
我有以下 html 片段:
<div onClick="javascript:getComments(this);" store-id="143568" class="CountryRow" style="padding: 4px;"><div class="flag flag_az"></div> Azerbaijan</div>
and I would like to create a jquery function to get the value of store-id
. I have the following however its not working :
我想创建一个 jquery 函数来获取store-id
. 我有以下但它不工作:
getComments = function(input) {
fValue = $(input).val( $(input).attr("store-id") );
alert('the ID :'+fValue);
}
can someone be kind enough to tell me what it is that I am doing wrong.
有人可以告诉我我做错了什么吗?
回答by samura
This works perfectly:
这完美地工作:
getComments = function(input) {
fValue = $(input).attr("store-id");
alert('the ID :'+fValue);
}
回答by P.Brian.Mackey
Take a look at jQuery custom selectors. Personally, I would use HTML5 data attributesfor cases such as this which is already supportedin jQuery.
看看 jQuery自定义选择器。就我个人而言,我会在 jQuery已经支持的情况下使用 HTML5数据属性。
For whatever it's worth, considering the parameter I believe what are you trying to originally perform should be done like
无论它的价值如何,考虑到参数,我相信您最初尝试执行的操作应该像
getComments = function(input) {
fValue = $(input).html( $(input).attr("store-id") );
alert('the ID :'+fValue.html());
}
回答by Pete K
all you have to do is :
你所要做的就是:
fValue = $(input).attr("store-id");
your snippet is trying to add to the 'value' attribute of a div (which does not exist)
您的代码段试图添加到 div 的“值”属性(不存在)