相关疑难解决方法(0)

.prop()vs .attr()

所以jQuery 1.6具有新功能prop().

$(selector).click(function(){
    //instead of:
    this.getAttribute('style');
    //do i use:
    $(this).prop('style');
    //or:
    $(this).attr('style');
})
Run Code Online (Sandbox Code Playgroud)

或者在这种情况下,他们做同样的事情?

如果我有转用prop(),所有的旧attr()电话,如果我切换到1.6将打破?

UPDATE

selector = '#id'

$(selector).click(function() {
    //instead of:
    var getAtt = this.getAttribute('style');
    //do i use:
    var thisProp = $(this).prop('style');
    //or:
    var thisAttr = $(this).attr('style');

    console.log(getAtt, thisProp, thisAttr);
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<div id='id' style="color: red;background: orange;">test</div>
Run Code Online (Sandbox Code Playgroud)

(另见这个小提琴:http://jsfiddle.net/maniator/JpUF2/)

控制台会记录getAttribute作为一个字符串,并attr作为一个字符串,但prop作为一个CSSStyleDeclaration,为什么?这对我未来的编码有何影响?

javascript jquery dom prop attr

2249
推荐指数
14
解决办法
57万
查看次数

写入data-*属性并使用jQuery .data()获取它

可能重复:
jQuery .data()不更新DOM

我在使用on属性时遇到问题.我写了一小组方法来发送api调用.

标记是这样的:

<div data-global-id="1318" data-action="unfollow" class="action text-as-link follow-btn btn" style="text-decoration: none;">unfollow</div>
Run Code Online (Sandbox Code Playgroud)

并有一个这样的事件捕获:

$(document).on('click','.action', function(){
  var t={};
  t.args={};
  t.args.global_id=$(this).data('global-id');
  t.global_id=t.args.global_id;
  t.action=$(this).data('action');
  t.identifier=t.action + '_v2';
  alert('here is action: ' + t.action);
  api_post_v1(t);
});
Run Code Online (Sandbox Code Playgroud)

api_post_v1正确发送呼叫.

有一些代码可以处理回调,它将标记设置为:

<div data-global-id="1318" data-action="follow" class="action text-as-link follow-btn btn" style="text-decoration: none;">follow</div>
Run Code Online (Sandbox Code Playgroud)

这个代码就像:

$foo=$('.action[data-action=unfollow][data-global-id='+global_id+']');
$foo.attr('data-action','follow');
Run Code Online (Sandbox Code Playgroud)

关键是数据动作.我希望上面的事件处理程序的调用说它是'跟随'但它说它仍然是'取消关注'.

顺序如下:

  1. 加载页面,data-action ='unfollow'
  2. 点击这个,api调用得到,你没有关注这个用户; 回调设置data-action ='follow'
  3. 再次单击此值,数据操作将回显为"取消关注"而不是"关注"

我怎么能告诉jQuery刷新这个事件的绑定?我认为这就是$(document).on的作用.

谢谢

jquery

10
推荐指数
1
解决办法
5513
查看次数

标签 统计

jquery ×2

attr ×1

dom ×1

javascript ×1

prop ×1