简体   繁体   English

使用一个按钮打开/关闭页面上的链接:toggle()两个功能

[英]Switch on / off Links on the page with one button: toggle() two functions

I've written a working code for the two buttons: 我已经为两个按钮编写了工作代码:

HTML: HTML:

<button class="OFF-LINK">OFF</button>
<button class="ON-LINK">ON</button>

<div class="box">...<a></a>...<a></a>...</div>
<div class="box">...<a></a>...<a></a>...</div>

Script: 脚本:

$(".OFF-LINK").click(function off() {
    var box = document.getElementsByClassName("box"); 
    var x; for (x = 0; x < box.length; x++) 
    {box[x].innerHTML = box[x].innerHTML.replace( /href/ig,'hren');}
}); ///links stop working

$(".ON-LINK").click(function on() {
    var box = document.getElementsByClassName("box"); 
    var y; for (y = 0; y < box.length; y++) 
    {box[y].innerHTML = box[y].innerHTML.replace( /hren/ig,'href');}
}); ///links work again

How can I combine this two functions, to toggle them with one button? 如何结合这两个功能,以一个按钮切换它们?

You can achieve this by checking the returned match from RegEx pattern inside .replace() and swap it as per the below snippet 您可以通过检查.replace() RegEx模式返回的匹配项并按照以下代码片段进行交换来实现此目的

 function toggleLinks() { var box = document.getElementsByClassName("box"); var x; for (x = 0; x < box.length; x++) { box[x].innerHTML = box[x].innerHTML.replace(/hre(f|n)/gi, g1 => {return (g1=="href") ? "hren" : "href"}); } } 
 <button onclick="toggleLinks()">Toggle Links</button> <div class="box"> <a href="http://www.google.com">google</a> <br> <a href="http://www.yahoo.com" >yahoo</a> </div> <div class="box"> <a href="http://www.stackoverflow.com"> stackoverflow</a> <br> <a href="http://www.github.com" >github</a> </div> 

I put some text in so you could see the changes 我输入了一些文字,以便您可以看到更改

 $(".OFF-LINK,.ON-LINK").on('click', function() { var box = document.getElementsByClassName("box"); var x; for (x = 0; x < box.length; x++) { box[x].innerHTML = $(this).is('.OFF-LINK') ? box[x].innerHTML.replace(/href/ig, 'hren') : box[x].innerHTML.replace(/hren/ig, 'href'); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button class="OFF-LINK">OFF</button> <button class="ON-LINK">ON</button> <div class="box">... <a>href</a>... <a>X</a>... </div> <div class="box">... <a>href</a>... <a>Y</a>... </div> 

How can I combine this two functions, to toggle them with one button? 如何结合这两个功能,以一个按钮切换它们?

If I'm understanding you correctly, you want to toggle the class on the button between on-link and off-link , and call the appropriate function afterwards? 如果我对您的理解正确,那么您想在on-linkoff-link之间切换按钮on-link的类,然后再调用适当的函数吗? If so: 如果是这样的话:

<button class="button off-link">Off</button>

$('body').on('click', '.button', function(){
  $(this).toggleClass('off-link on-link');
  if ($(this).hasClass('off-link')) {
    $(this).innerHTML('Off');
    // Do your 'off-link' code here
  } else {
    $(this).innerHTML('On');
    // Do your 'on-link' code here
  }
});

Generally, it's bad practice to replace all innerHTML, just to change a little detail. 通常,替换所有innerHTML只是更改一些细节是不好的做法。 If you need to toggle links, would be better to find the required links and work only with their attributes: 如果需要切换链接,最好找到所需的链接并仅使用它们的属性:

 $('.box a').each(function(){ var link = $(this).attr("href"); $(this).attr("data-link", link); // saving each link in data-attribute }); $('#toggle').on('click', function toggler(){ let on = toggler.on = !toggler.on; // (*1) $('.box a').each(function(){ var link = $(this).attr("data-link"); $(this)[ on ? "removeAttr" : "attr" ]( "href", link ); // (*2) }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="toggle">Toggle Links</button> <div class="box"> <a href="https://google.com" target="_blank">link</a> <a href="https://google.com" target="_blank">link</a> </div> <div class="box"> <a href="https://google.com" target="_blank">link</a> <a href="https://google.com" target="_blank">link</a> </div> 

(*1) let on = toggler.on = !toggler.on; (* 1) let on = toggler.on = !toggler.on; — each function is an object. —每个函数都是一个对象。 You can work with it's name just like with common objects - setting him new properties or methods. 您可以像处理普通对象一样使用它的名称-为他设置新的属性或方法。 I could declare a variable let on = true; 我可以声明一个变量let on = true; out of the function, but decided to make everything inside. 退出功能,但决定将所有内容放到里面。 ! — it's the boolean "NOT": transforms falsetrue and vice versa. —是布尔值“ NOT”:转换为falsetrue ,反之亦然。 So, when you click the button, toggler.on is undefined (false), ! 因此,当您单击按钮时, toggler.on是未定义的(false) ! will become true and assign to itself ( toggler.on = !toggler.on; ) → the same value will be assigned to variable on . 将变为true并分配给自己( toggler.on = !toggler.on; )→将相同的值分配给on变量。

At the next click, property toggler.on already will keep the true value, and become !true → false , and so on. 下次单击时,属性toggler.on已经保留了true值,并变为!true → false ,依此类推。

(*2) $(this)[ on ? "removeAttr" : "attr" ]( "href", link ); (* 2) $(this)[ on ? "removeAttr" : "attr" ]( "href", link ); $(this)[ on ? "removeAttr" : "attr" ]( "href", link );

Ternary operator , general form: (boolean expression) ? (return this value if true) : (else) 三元运算符 ,一般形式:( (boolean expression) ? (return this value if true) : (else) (boolean expression) ? (return this value if true) : (else)

In this example, expression will return a "removeAttr" string, if on === true , and "attr" otherwise. 在此示例中,如果on === true ,则expression将返回“ removeAttr”字符串,否则返回“ attr”。

Bracket notation . 括号符号 Mostly we use the dot notation , because it's shorter. 通常,我们使用点符号 ,因为它更短。 Example, elem.innerHTML may be written as elem["innerHTML"] . 例如, elem.innerHTML可以写为elem["innerHTML"] Here I used a ternary expression, to pick the required method. 在这里,我使用了三元表达式来选择所需的方法。 Translation into if-else: 转换为if-else:

if( on ){
  $(this).removeAttr("href")
} else {
  var link = $(this).attr("data-link");
  $(this).attr("href", link );
}

And the same code without jQ: 和没有jQ的相同代码:

 let links = document.querySelectorAll('.box a'); for( let i = 0; i < links.length; i++ ){ links[i].dataset.link = links[i].getAttribute("href"); } let toggle = document.getElementById('toggle'); toggle.addEventListener('click', function toggler(){ let on = toggler.on = !toggler.on; for( let i = 0; i < links.length; i++ ){ let link = links[i].dataset.link; links[i][ on ? "removeAttribute" : "setAttribute"]("href", link); } }); 
 <button id="toggle">Toggle Links</button> <div class="box"> <a href="https://google.com" target="_blank">link</a> <a href="https://google.com" target="_blank">link</a> </div> <div class="box"> <a href="https://google.com" target="_blank">link</a> <a href="https://google.com" target="_blank">link</a> </div> 

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

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