简体   繁体   English

循环 <article> 在html页面中

[英]looping through <article> in the html page

I have to loop through <article> tag in the Html file and add its classname when clicked and then remove the class name in all other <article> tags 我必须遍历Html文件中的<article>标记,并在单击时添加其类名,然后删除所有其他<article>标记中的类名

for eg: 例如:

 <article onclick="javascript:selectthis(this)">
1
</article>
<article onclick="javascript:selectthis(this)">
11
</article>
<article onclick="javascript:selectthis(this)">
111
</article>
<article onclick="javascript:selectthis(this)">
1111
</article>
<article onclick="javascript:selectthis(this)">
11111
</article>

<script>
function selectthis(THIS) {

 THIS.className = "countrySelected";

  }
</script>

is there a way to loop through the tags and remove the classnames except for the recent one that is clicked? 有没有办法循环标记并删除类名,除了最近点击的类名? What is the best possible way to do ? 什么是最好的方法? Should I really have to add a onclick event attached to every <article> tag? 我是否真的必须添加附加到每个<article>标签的onclick事件? because there could be many <article> tag in the html file. 因为html文件中可能有很多<article>标签。 I really donot want to add this onclick event to every article tag. 我真的不想将这个onclick事件添加到每个文章标签中。

any help would be appreciated. 任何帮助,将不胜感激。

You didn't tag jQuery , but I'd recommend using that in this particular case, where event bubling and filtering plays nice. 你没有标记jQuery ,但我建议在这种特殊情况下使用它,事件冒泡和过滤效果很好。 Instead of register multiple click-handlers (as you point out) you can register one soley, and have that one in common for all elements. 而不是注册多个点击处理程序(正如你指出的那样),你可以注册一个soley,并为所有元素共同使用。 jQuery is good at filtering out events to a specific selector as well. jQuery也擅长将事件过滤到特定的选择器。 I'd give it a shot. 我试一试。

Here's an example of how to solve your issue using jQuery: 以下是如何使用jQuery解决问题的示例:

// Register an event-handler on document, that listens for a 'click' event.
// Only pick up the event from the selector 'article' though, which corresponds
// to only article elements on the page.
$(document).on('click', 'article', function(){
    this.className = "countrySelected"; // this in this context, is the actual DOM-element
});

Then for your issue of removing the className for all articles, not having the class countrySelected . 然后为你的问题删除所有文章的className ,没有class countrySelected This also is nice with jQuery as such: 这也适用于jQuery:

// Find all article-elements, that DON'T have the class countrySelected
// Then remove _all_ the classes it has
// To remove a specific class, use .removeClass('classToRemove')
$('article').not('.countrySelected').removeClass();

So in the end, you can combine the two and make this: 所以最后,你可以结合这两个并做到这一点:

$(document).on('click', 'article', function(){
    $('article').removeClass(); // Remove class from all other first
    this.className = "countrySelected"; // this in this context, is the actual DOM-element
});

Add this jquery: 添加此jquery:

$("article").click(function() {
  $("article").toggleClass("countrySelected");
});

Example code snippet: 示例代码段:

 $("article").click(function() { $(".countrySelected").removeClass("countrySelected"); $(this).addClass("countrySelected"); }); 
 article.countrySelected { background-color: orange; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <article>This is article 1</article> <article>This is article 2</article> <article>This is article 3</article> <article>This is article 4</article> <article>This is article 5</article> <article>This is article 6</article> 

Since you didn't tag this jquery, here is a pure javascript solution: 由于你没有标记这个jquery,这里是一个纯粹的javascript解决方案:

window.onload = function() {
  // This is a list of all the articles on the page
  var articles = document.querySelectorAll("article");
  for (var i = 0; i < articles.length; ++i) {
    // Loop through each article
    var article = articles[i];
    // Add an event listener for each one
    article.addEventListener("click", function() {
      // Get the previously selected one and deselect it
      var prevSelected = document.querySelector(".countrySelected");
      if (prevSelected != null) prevSelected.classList.remove("countrySelected");
      this.classList.add("countrySelected"); // or for older browsers: this.className = "countrySelected";
    }, false);
  }
}

 window.onload = function() { var articles = document.querySelectorAll("article"); for (var i = 0; i < articles.length; ++i) { var article = articles[i]; article.addEventListener("click", function() { var prevSelected = document.querySelector(".countrySelected"); if (prevSelected != null) prevSelected.classList.remove("countrySelected"); this.classList.add("countrySelected"); // or for older browsers: this.className = "countrySelected"; }, false); } } 
 .countrySelected { background-color: orange; } 
 <article>Article 1</article> <article>Article 2</article> <article>Article 3</article> <article>Article 4</article> <article>Article 5</article> 

Assuming you do place an onclick on each article .. inside of your function, you could do this: 假设您在每个文章上放置了一个onclick ..在函数内部,您可以这样做:

function selectthis(THIS) {

    //remove the css classes from all articles
    var articles=document.getElementsByTagName('article');
    for(var a=0;a<articles.length;a++){
        articles[a].setAttribute('class','');
    }

    //add class back on for this article
    THIS.className = "countrySelected";
}

I'll treat it this way without using jQuery. 我会这样对待它而不使用jQuery。 The reason why is this way in the future it is far more easier to understand why certain stuff happens. 之所以这样,将来会更容易理解为什么会发生某些事情。 And sometimes basic JS is far more fitting for using a small adjustment instead of a bloated library. 有时基本的JS更适合使用小调整而不是膨胀的库。

The best way is to start, is at the moment nothing still happened and the page just loaded. 最好的方法是启动,目前还没有发生任何事情,只是加载了页面。 Instead of using the javascript inline with an onclick. 而不是使用内嵌onclick的javascript。 First assign an event-listener. 首先分配一个事件监听器。

Page Loaded 页面已加载

With Element.getElementsByTagName() you can get all the needed elements and go for a loop. 使用Element.getElementsByTagName(),您可以获得所有需要的元素并进行循环。 documentation ; 文件 ;

So you get 所以你得到了

var articleTags = document.getElementsByTagName('ARTICLE');

In this case we can use a simple loop 在这种情况下,我们可以使用简单的循环

var articleDOM = null;
for(var i = 0; i < articlesTags.length; i++){
    articleDOM = articlesTags[i];
    articleDOM.addEventListener("click", addClassToArticleFunction);
)

Each article now has an event binded with a function. 现在每篇文章都有一个用函数绑定的事件。 Let's define that function. 让我们定义那个功能。

Add Class Function 添加类功能

I'll use ' addClassToArticleFunction ', but you can of course make it even more generic in name. 我将使用' addClassToArticleFunction ',但你当然可以使它在名称上更通用。 Could be you want also use this function for other tags or DOM-elements. 也许你想要将此函数用于其他标签或DOM元素。

function addClassToArticleFunction(){
    this.className = "countrySelected";

}

Each time this will be called the class will be defined. 每次调用此类时都将定义该类。 Only you off course get a problem by all of them will get that classname. 只有你当然会遇到问题所有人都会获得该类名。

So lets just call a function that will do all the deleting. 因此,我们只需调用一个将执行所有删除操作的函数。

function addClassToArticleFunction(){
    deleteClassNameFromArticles();
    this.className = "countrySelected";
}


function deleteClassNameFromArticles(){
     //deletion here
}

Since we know all the articles already, and know how to calls the classname it is an easy copy paste 由于我们已经知道所有文章,并且知道如何调用类名,因此它是一个简单的复制粘贴

for(i = 0; i < articleTags.length; i++){
    articleDOM = articleTags[i];
    articleDOM.className = "";
}  

At this point it is done. 此时已完成。

Recap 概括

  • load window 加载窗口
  • assign event listeners to articles 为文章分配事件监听器
  • when clicked on article a function will be called 当点击文章时,将调用一个函数
  • this function will delete all classnames from articles 此函数将删除文章中的所有类名
  • this function will assign on the clicked article a classname 此函数将在单击的文章上分配一个类名

JS fiddle to see it work JS小提琴看它有效

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

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