javascript - 如何选择被点击的行

标签 javascript css

我想要一个元素列表,其中选定元素的颜色在被选中时变为红色,而所有其他 div 变为蓝色。我如何识别随后会变成红色的选定 div?

$(document).ready(function() {
  $('#table_1 .tableRow div').click(function(event) {

    //Set the style for all divs
    var myElements = document.querySelectorAll("#table_1 .tableRow div");
    for (var i = 0; i < myElements.length; i++) {
      myElements[i].className = "blueText";
    }
    //Set the style for tyhe selected div
    //selectedItem.className="selectedText";
  });
});
.selectedText {
  color: red;
}
.blueText {
  color: blue;
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>

<body>

  <div id="table_1" class="table">
    <div class="tableRow">
      <div>
        Line 1
      </div>
      <div>
        Line 2
      </div>
      <div>
        Line 3
      </div>
    </div>
  </div>
</body>

</html>

最佳答案

改变就够了:

//selectedItem.className="selectedText";

到:

event.target.className="selectedText";

片段:

$(document).ready(function(){
  $('#table_1 .tableRow div').click(function(event) {

    //Set the style for all divs
    var myElements = document.querySelectorAll("#table_1 .tableRow div");
    for (var i = 0; i < myElements.length; i++) {
      myElements[i].className="blueText";
    }
    //Set the style for tyhe selected div
    event.target.className="selectedText";
  });
});
.selectedText {
  color: red;
}
.blueText {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div  id="table_1" class="table">
    <div class="tableRow">
        <div>
            Line 1
        </div>
        <div >
            Line 2
        </div>
        <div >
            Line 3
        </div>
    </div>
</div>

关于javascript - 如何选择被点击的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40616241/

相关文章:

javascript - SQLite 和 Javascript : Checking for existence of data before inserting OR letting SQLite throw an exception

javascript - 如何让我的页面自动提交?

javascript - 调整 JavaScript 数组中幻灯片图像的大小以适合视口(viewport)

javascript - 自定义排序对象数组

javascript - ecmascript 规范的语法令人困惑

html - 禁用 Shockwave 播放器中的暂停按钮

html - 如何在不产生插入效果的情况下为输入框着色

html - 使用 dojo/html/css 实现搜索栏/按钮?

javascript - 单击kengo网格行内的kendo图表

html - 如何在父 div 中对齐两个 div( Logo 和菜单)?