繁体   English   中英

jQuery更改属性并将其更改回来

[英]jQuery changing attribute and changing it back

我希望在用户单击按钮之前无法访问页面上的所有链接。

$('a').attr('href','#');

$("#button-yes").click(function(){
    $('a').attr('href',function(){
        $(this).attr('href');
    });
});

如何跟踪状态而不是重写所有href?

var buttonClicked = false;

$('a').click(function(){
  if(! buttonClicked) {
    return false;
  }
});

$("#button-yes").click(function(){
    buttonClicked = true;
});

在函数外面有一个var,它说:

button_clicked = false;

然后使用它来禁用所有链接

$('a').click(function(){
   if(!button_clicked){
      return false;
   }
});

返回false将导致链接无效。

您需要隐藏href的值,以便以后可以恢复它。 我将href值存入rel属性。

$('a').each(function(){
    $(this).attr('rel', $(this).attr('href'));  //store the href values
    $(this).attr('href', '');  //clear the href values
});

$("#button-yes").click(function(){
    $('a').each(function(){
        $(this).attr('href', $(this).attr('rel'));  //recover the href values
    });
});

这是一种简单的方法,但它将地址保留在rel属性中。 一个聪明的用户可能会发现并使用它来绕过你的按钮,所以这是@rsp建议的另一种方法。

$('a').each(function(){
    $(this).data('link', $(this).attr('href'));  //store the href values
    $(this).attr('href', '');  //clear the href values
});

$("#button-yes").click(function(){
    $('a').each(function(){
        $(this).attr('href', $(this).data('link'));  //recover the href values
    });
});

通过使用.data()存储href,链接地址更加模糊,因此用户不应该轻易绕过按钮(尽管禁用JavaScript将完全避开这一点)。

最简单的例子是劫持所有链接的click事件:

$('a').live('click.disable', function() {
    return false;
});

$("#button-yes").click(function() {
    $('a').die('click.disable');
});

(请参阅此小提琴: http//jsfiddle.net/A6QPn/ )但任何人都可以右键单击该链接并在新选项卡中打开它或类似的东西。

另一个例子是将href属性存储为数据并在以后恢复它们:

$('a').each(function() {
    var $this = $(this);
    $this.data('href', $this.attr('href'));
    $this.attr('href', '#');
});

$("#button-yes").click(function() {
    $('a').each(function() {
        var $this = $(this);
        $this.attr('href', $this.data('href'));
    });
});

(见这个小提琴: http//jsfiddle.net/eQDdQ/ )这里的链接不起作用,因为它们都指向当前页面上的“#”。

另一个例子是基本上做同样的事情,但完全删除href属性使链接看起来像普通文本,直到单击按钮:

$('a').each(function() {
    var $this = $(this);
    $this.data('href', $this.attr('href'));
    $this.removeAttr('href');
});

$("#button-yes").click(function() {
    $('a').each(function() {
        var $this = $(this);
        $this.attr('href', $this.data('href'));
    });
});

(见这个小提琴: http//jsfiddle.net/gmLTP/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM