当我用不同的按钮调用时,如何更改JS函数的功能?

时间:2017-08-09 16:12:25

标签: javascript html performance

我正在学习Javascript,而我正在尝试清理我的代码。代码非常简单:只需单击一些不同的按钮即可更改某些文本的颜色。当您单击红色按钮时,文本变为红色,蓝色按钮,文本变为蓝色等。以下是代码:

HTML:

<h1 id="title">Change my color!</h1>

<button id="btn" onclick="colorRed()">Red</button>
<button id="btn" onclick="colorGreen()">Green</button>
<button id="btn" onclick="colorBlue()">Blue</button>
<button id="btn" onclick="colorBlack()">Black</button>

使用Javascript:

var title = document.getElementById("title");

function colorRed() {
  title.style.color = "red";
}

function colorGreen() {
  title.style.color = "green";
}

function colorBlue() {
  title.style.color = "blue";
}

function colorBlack() {
  title.style.color = "black";
}

此代码有效。我的问题是如何清理我的Javascript;在我将拥有20个按钮的情况下,编码20种不同的功能显然不是可行的方法。

我确实为每种颜色尝试了以下颜色,但这不起作用:

使用Javascript:

var title = document.getElementById("title");

var btn = document.getElementById("btn");

function changeColor() {
  if(btn.innerHTML == "Red") {
    title.style.color = "red";
  } else if ...
}

我认为当我尝试通过查看其内部HTML是否等于某种颜色来识别哪个按钮时出错了,但我不确定如何解决这个问题。非常感谢帮助!

编辑:我的问题不是Change an element's background color when clicking a different element的重复,因为我编写的代码已经完成,我只是想学习如何清理它。

6 个答案:

答案 0 :(得分:4)

最简单的方法是制作一个changeColor函数并在事件中传递颜色:

var title = document.getElementById("title");

function changeColor(color) {
   console.log(color);
   title.style.color = color;
}
<h1 id="title">Change my color!</h1>

<button class="btn" onclick="changeColor('red')">Red</button>
<button class="btn" onclick="changeColor('green')">Green</button>
<button class="btn" onclick="changeColor('blue')">Blue</button>
<button class="btn" onclick="changeColor('black')">Black</button>

旁注:您真的不应该重复id,而应该使用class

通常不建议使用内联事件处理程序,而是使用addEventListener。我不建议为每个元素添加一个事件监听器,而是建议添加一个公共父元素,将一个事件监听器附加到该元素并检查事件("event delegation")以确定要应用的颜色:

var title = document.querySelector('#title');

document.querySelector('#button-container').addEventListener('click', function(event) {
   var color = event.target.getAttribute('data-color')
   title.style.color = color;
}, false)
<h1 id="title">Change my color!</h1>
<div id="button-container">
  <button data-color="red">Red</button>
  <button data-color="green">Green</button>
  <button data-color="blue">Blue</button>
  <button data-color="black">Black</button>
</div>

答案 1 :(得分:4)

不要使用内联HTML事件属性,例如onclick。有一个 variety of reasons why ,如果您刚刚开始使用JavaScript,那么您不希望发现任何不良习惯。相反,请将您的JavaScript与HTML完全分开,并使用 .addEventListener() JavaScript方法设置事件处理程序,以遵循现代标准。

此外,id值在文档中必须是唯一的(它们的唯一要点是唯一标识元素)。为了能够只对与此操作相关的按钮进行分组,您可以为它们提供所有相同的CSS类,然后在JavaScript中查询该类(如下所示)。

接下来,您只需要一个函数,但是如果您的各个按钮存储了它们应该生成的颜色,那么一个函数可以提取它并使用它而无需将任何参数传递给您的函数:

var title = document.getElementById("title");

// When you query your document for groups of matching elements (using methods
// like: getElementsByTagName or getElementsByClassName) you get back an object
// that is similar to an array, called a "node list". Although these "array-like"
// objects support some of the standard array object's features, they are not
// true arrays and don't implement many of the powerful array methods out there.

// But, we can convert the node list returned from .querySelectorAll into an array
// and then we can iterate the array with .forEach() looping method later.
var buttonArray = Array.prototype.slice.call(document.querySelectorAll(".colorBtn"));

// Loop through the button array (the function provided as an argument will be 
// executed for each element in the array)
buttonArray.forEach(function(button){
  
  // Set up click event handlers for each button
  button.addEventListener("click", function(){
    // Just set the color to the "data-color" attribute value on the element
    title.style.color = button.dataset.color;
  })

});
.colorBtn {
  box-shadow:2px 2px 1px grey;
  border-radius:4px; 
  width:100px;
  display:inline-block;
  margin:4px; 
}

.colorBtn:hover, .colorBtn:active {
  box-shadow:-2px -2px 1px #e0e0e0;
  outline:none;
}
<h1 id="title">Change my color!</h1>

<!-- Putting related elements into the same class allows you to
     not only style them identically, but also find them in 
     JavaScript more easily. -->
<button id="btn1" class="colorBtn" data-color="red">Red</button>
<button id="btn2" class="colorBtn" data-color="green">Green</button>
<button id="btn3" class="colorBtn" data-color="blue">Blue</button>
<button id="btn4" class="colorBtn" data-color="black">Black</button>

答案 2 :(得分:1)

另一种方法是:

function changeColor() {
    title.style.color = btn.style.backgroundColor;
}

并将每个按钮背景设置为适当的颜色。

答案 3 :(得分:1)

您可以将该颜色传递给changeColor函数,而不是让函数找出要更改的颜色。你的职能将成为:

function changeColor(color) {
    title.style.color = color;
}

然后在您的HTML中,您将更改onclick属性以将其传递到:

<button id="btn" onclick="changeColor('red')">Red</button>
...

另外,我想提一下,之前您的问题不仅仅与您在帖子中建议的innerHTML相关。一个问题是您有多个具有相同id的HTML元素。使用document.getElementById()时,这不会很好。

答案 4 :(得分:0)

当您需要动态数量的元素时,我们需要一种简单的方法在DOM中找到它们。有一些辅助方法,如getElementsByClassName()对象上的document。我要做的第一件事就是删除按钮上的ID(顺便说一句,它应该是唯一的),而不是类名:

<button class="btn" onclick="colorRed()">Red</button>
<button class="btn" onclick="colorGreen()">Green</button>
<button class="btn" onclick="colorBlue()">Blue</button>
<button class="btn" onclick="colorBlack()">Black</button>

我要做的第二件事就是重构这个,以便你可以使用良好的不引人注目的JavaScript实践(基本上从HTML标记中获取JavaScript并在JavaScript代码块中将其连接起来)。首先,我们需要一种方法让JavaScript知道要将按钮文本更改为哪种颜色。我们将引入自定义HTML data-属性来代替硬编码的onclick处理程序:

<button class="btn" data-color="red">Red</button>
<button class="btn" data-color="green">Green</button>
<button class="btn" data-color="blue">Blue</button>
<button class="btn" data-color="black">Black</button>

现在,我们需要一种方法来查找这些按钮,以便我们可以循环它们并应用onclick处理程序。这可以用我前面提到的方法完成:

var title = document.getElementById("title");
var buttons = document.getElementsByClassName("btn");

这将为您构建四个按钮的数组(或者您拥有的多个按钮)。

然后我们需要循环遍历它们并分配一个单击处理程序,该处理程序从data-color属性中检索颜色并将其分配给<h1>元素的style.color属性:

for (var btnIndex = 0; btnIndex < buttons.length; btnIndex++)
{
    buttons[btnIndex].onclick = function() {
        title.style.color = this.getAttribute('data-color');
    }
}

就是这样!我们消除了所有重复,并同时练习了一些更好的JavaScript技术。试试下面的代码:

var title = document.getElementById("title");
var buttons = document.getElementsByClassName("btn");

for (var btnIndex = 0; btnIndex < buttons.length; btnIndex++)
{
    buttons[btnIndex].onclick = function() {
        title.style.color = this.getAttribute('data-color');
    }
}
<h1 id="title">Change my color!</h1>

<button class="btn" data-color="red">Red</button>
<button class="btn" data-color="green">Green</button>
<button class="btn" data-color="blue">Blue</button>
<button class="btn" data-color="black">Black</button>

答案 5 :(得分:-1)

<h1 id="heading">Change My Color</h1>
<button id="btn" onclick="change('green');">Green</button>
<button id="btn" onclick="change('red');">Red</button>
<button id="btn" onclick="change('yellow');">Yellow</button>
<button id="btn" onclick="change('blue');">Blue</button>
<script type="text/javascript">
    function change(val)
    {
        col=val;
        document.getElementById("heading").style.color=col;
    }
</script>