答案 0 :(得分:1)
调用attr(key)
将获取元素的属性。 如果存在,则值始终为String。
调用attr(key, value)
将在元素上设置属性,并且不会更新任何jQuery缓存。
调用data(key)
将从jQuery缓存中获取数据元素。如果找不到,它将从属性中获取值并将其缓存以供将来的请求使用。 它还会尝试自动将字符串解析为它可以使用的任何类型,因此该值不一定是字符串。
调用data(key, value)
将在缓存中设置值,并且不会更新元素上的属性。
var $button = $('button');
//set the attribute on the element
$button.attr('data-test1', 'hi');
//First time call with attr get, value will be correct
//First time call with data get, value will be correct as it falls back to getting the attr value
console.log( 'Set with attr =>', $button.attr('data-test1'), $button.data('test1'));
//set the data value in the jQuery cache. does not change any attribute
$button.data('test2', 'hi2');
//First time call with attr get, value will be undefined
//First time call with data get, value will be correct
console.log( 'Set with data =>', $button.attr('data-test2'), $button.data('test2'));
//modify the attr after data() has already been called
$button.attr('data-test1', 'new value');
//Second time call with attr get, value will be correct
//Second time call with data get, value will be incorrect as it has the previously cached value that is not updated with attr()
console.log( 'Set with attr =>', $button.attr('data-test1'), $button.data('test1'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Blah</button>