Jquery不能在href标签中工作吗?

时间:2018-02-23 14:44:39

标签: jquery

我一直在尝试为href标签添加切换功能。这段代码工作正常。

首先单击链接时,将文本更改为“删除库”文本并调用该函数。同样单击“删除库”,文本已更改并调用该函数。

但是在“删除库文本”阶段重新加载页面时,显示默认文本,但功能正常。

<a href="javascript:void(0);" class="example">Add to Library</a>

我已经在document.write()函数中编写了这个jquery。

var clicked = true;
 $("#example").click(function(e){
   e.preventDefault();
if(clicked){
   var personal_lib_checked = $('#example').attr('class');
   add_to_function(personal_lib_checked, 'add');
   $(this).text('Remove from Library');
   clicked  = false;
 } else {
   var personal_lib_checked = $('#example').attr('class');
   add_to_function(personal_lib_checked, 'remove');
   $(this).text('Add to Library');
   clicked  = true;
   }  
});

如何重新加载页面,如何显示当前显示的文字?

使用localStorage后,仍面临同样的问题

var clicked = true;
 $(".example").click(function(e){
   e.preventDefault();
if(clicked){
   var personal_lib_checked = $('.example').attr('class');
   add_to_function(personal_lib_checked, 'add');
   localStorage.setItem("removefromlibrary", "Remove From Library");
   var removefromlibrary = localStorage.getItem("removefromlibrary");
   $(this).text(removefromlibrary);
   //checked only for this condition
   clicked  = false;
 } else {
   var personal_lib_checked = $('.example').attr('class');
   add_to_function(personal_lib_checked, 'remove');
   $(this).text('Add to Library');
   clicked  = true;
   }  
});

请有人指导我解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

我没有解释为什么会发生这种情况,但是你可以做到这一点,它会很棒。

var added = false;

function setLibraryText(that) {
  var result;
  if(added == true) result = "Add to Library";
  else result = "Remove from Library";
  
  added = !added;
  $(that).text(result);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a onclick="return setLibraryText(this);" href="javascript:void(0);" class="example">Add to Library</a>

答案 1 :(得分:0)

不知道为什么你确实需要这个,但是这个会起作用。 Working demo

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:void(0);" class="example">Add to Library</a>

Js

var clicked = (localStorage.getItem("status")=="false")?localStorage.getItem("status"):"true";
var hrefText;
var add="Remove From Library";
var remove="Add to Library";
if(clicked=="true"){
  clicked=true; 
  hrefText=add;
}else{
  clicked=false
  hrefText=remove;
}
$(".example").text(hrefText);
console.log(clicked);

$(".example").click(function(e){
  e.preventDefault();
  if(clicked){
     clicked  = false;
     var personal_lib_checked = $(this).attr('class');
     //add_to_function(personal_lib_checked, 'add');
     localStorage.setItem("status", clicked);
     $(this).text(remove);
     //checked only for this condition
   } else {
     clicked  = true;
     var personal_lib_checked = $(this).attr('class');
     //add_to_function(personal_lib_checked, 'remove');
     localStorage.setItem("status", clicked);
     $(this).text(add);
   }  
});