2

我已经在使用 id 和 title 但我需要再解析 2 位...

$(this).attr("title"); $(this).attr("id");

$(this).attr("custom1");工作吗??

4

5 回答 5

3

是的,顺便说一句,您可以一次设置多个属性:

$('.myselector').attr({
src: 'thefile.gif',
width: 200,
height: 300 });
于 2011-03-07T18:15:13.900 回答
2

是的,您可以将它用于data-attributesHTML5 中的所有内容。这是添加额外属性的首选方式。

此外,所有data-*属性都会自动添加到 jQuery 的data()对象中,以便于访问

于 2011-03-07T18:12:27.867 回答
1

如果您只想(按名称)将某些数据与 DOM 元素相关联,最好使用“.data()”方法:

$(this).data('custom1', someValue);

“.data()”API 使编码到 HTML 中的 HTML5 样式的“data-foo”属性可访问:

var foo = $(this).data('foo'); // gets the "data-foo" attribute value from element
于 2011-03-07T18:13:50.883 回答
0

是的,它有效,但这不是一个好主意。

更好地使用.data('foo', 'bar'); 如果您想在元素上存储一些数据。

于 2011-03-07T18:14:10.300 回答
0

是的,你能做的最好的事情就是测试它。

<script>
$(document).ready(function() {
  // Handler for .ready() called.
  alert( "custom1 = " + $("#myField").attr("custom1") );
});
</script>

<div id="myField" custom1="My Custom Field"></div>

现在,您正在破坏标记,因此我建议将您的信息存储在 ALT 标记或 NAME 标记中以防止发生这种情况 ()。

于 2011-03-07T18:15:13.683 回答