简体   繁体   English

Javascript - 在点击给定的 class 后显示一个给定的 class 的 div

[英]Javascript - Show a div with a given class after clicking on a given class

Several spans that have certain classes.具有某些类的几个跨度。

<span class="1 click-1">1</span>
<span class="2 click-2">2</span>
<span class="3 click-3">4</span>
<span class="4 click-4">4</span>

Clicking on a given <span> displays a DIV that contains the same class. How to do it?单击给定的<span>会显示一个包含相同 class 的 DIV。该怎么做?

<div class="click-1">Hello!</div>
<div class="click-2">Hello 2!</div>
<div class="click-3">Hello 3!</div>
<div class="click-4">Hello 4!</div>

I need such a solution because it is development on the CMS side.我需要这样的解决方案,因为它是 CMS 端的开发。 User can add much more span and div.用户可以添加更多的 span 和 div。 So the script has to be universal.所以脚本必须是通用的。

Looking for something like this?寻找这样的东西?

 document.querySelectorAll("span").forEach(e => { e.onclick = () => { \/\/ on click on span const div = document.createElement("div"); \/\/ create new div div.classList = e.classList; \/\/ copy and reuse class list div.innerText = `Hello ${e.innerText}!`; \/\/ set inner text to 'Hello ${}!' document.body.append(div); \/\/ append div to dom } })<\/code><\/pre>
 span { display: block; }<\/code><\/pre>
 <span class="1 click-1">1<\/span> <span class="2 click-2">2<\/span> <span class="3 click-3">4<\/span> <span class="4 click-4">4<\/span> Clicking on a given <span> displays a DIV that contains the same class. How to do it?<\/code><\/pre>

"

Since JQuery is tagged, points to note is that only the span's 2nd class name will be used to find div with same classes in code below.由于标记了 JQuery,因此需要注意的是只有跨度的第二个 class 名称将用于在下面的代码中查找具有相同类的 div。

$(document).on("click","span",function(){// attaching evt listner to all spans
  var getClass = $(this).prop('class').split(' ')[1];//get 2nd classname of span
    $(`div.${getClass}`).show(); // divs with such class
    //or
    $(`.${getClass}`).show(); // anything with such class
});

This code will work with the html syntax given above.此代码将使用上面给出的 html 语法。 But in cases where there are just one class in a span then it will not work.但是在一个跨度中只有一个 class 的情况下,它将不起作用。 So modify the code accordingly or make sure the second class of span is equal to classname of div you are trying to show.因此相应地修改代码或确保 span 的第二个 class 等于您要显示的 div 的类名。

var testElements = document.getElementsByClassName('click-1');
var testDivs = Array.prototype.filter.call(testElements, function(testElement){
  return testElement.nodeName === 'DIV';
});

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

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