DOM具有相同功能的多个ID

时间:2019-03-11 15:30:25

标签: javascript html function addeventlistener

如何使ID使用相同的功能? 我打算用相同的功能制作更多的元素,但不想制作更多的功能。

 var star_1 = document.getElementById("star1");
    var star_2 = document.getElementById("star2");

    var toggle = false;

    favToggle = function() {


        if (toggle === true) {
            star_1.src = "assets/svg/checked-star.svg";

        } else {
            star_1.src = "assets/svg/unchecked-star.svg";
        }

        toggle = !toggle;
    }

     favToggle1 = function() {


        if (toggle === true) {
            star_2.src = "assets/svg/checked-star.svg";

        } else {
            star_2.src = "assets/svg/unchecked-star.svg";
        }

        toggle = !toggle;
    }

    star_1.addEventListener("click", favToggle);
    star_2.addEventListener("click", favToggle1);

4 个答案:

答案 0 :(得分:4)

// Number of stars you have
const nbStars = 4;

// An array where we keep the toggle state of each star
const toggles = [];

// Deal with the stars. One by one
for (let i = 0; i < nbStars; i += 1) {
  // Setup the initial state of the toggle
  toggles.push(false);

  const star = document.getElementById(`star${i + 1}`);

  star.addEventListener('click', () => {
    if (toggles[i] === true) {
      star.innerHTML = 'assets/svg/checked-star.svg';
    } else {
      star.innerHTML = 'assets/svg/unchecked-star.svg';
    }

    // Change the state of the toggle for that particular star
    toggles[i] = !toggles[i];
  });
}
.star {
  height: 5em;
  width 5em;
  background-color: #444444;
  margin: 1em;
  color: white;
}
<div id="star1" class="star"></div>
<div id="star2" class="star"></div>
<div id="star3" class="star"></div>
<div id="star4" class="star"></div>


使用@brk关于querySelectorAll的好主意的替代方法

const toggles = Array.from(document.querySelectorAll('[id^="star"]')).map((x, xi) => {
  x.addEventListener('click', () => {
    if (toggles[xi] === true) {
      x.innerHTML = 'assets/svg/checked-star.svg';
    } else {
      x.innerHTML = 'assets/svg/unchecked-star.svg';
    }

    // Change the state of the toggle for that particular star
    toggles[xi] = !toggles[xi];
  });

  // Setup the initial state of the toggle
  return false;
});
.star {
  height: 5em;
  width 5em;
  background-color: #444444;
  margin: 1em;
  color: white;
}
<div id="star1" class="star"></div>
<div id="star2" class="star"></div>
<div id="star3" class="star"></div>
<div id="star4" class="star"></div>

答案 1 :(得分:1)

您可以使用通配符选择器。在此示例中,它将选择以id开始的所有star元素。然后遍历每个对象,并向其中添加事件监听器

document.querySelectorAll("[id^='star']").forEach(function(elem) {
  this.addEventListener("click", favToggle);
})

function favToggle() {
  console.log('Button clicked')
}
<button id='star1'>Button 1</button>
<button id='star2'>Button 2</button>
<button id='star3'>Button 3</button>
<button id='star4'>Button 4</button>

答案 2 :(得分:0)

使用querySelectorAll()来同时获得"#star1,#star2"。然后对每个元素使用forEach()addEventListener()

var stars = document.querySelectorAll("#star1,#star2");
stars.forEach(i => {
  i.addEventListener("click",function(){
    if (toggle === true) {
        this.src = "assets/svg/checked-star.svg";
    } else {
        this.src = "assets/svg/unchecked-star.svg";
    }
    toggle = !toggle;
  })
})

答案 3 :(得分:0)

编写功能的目的是为了能够轻松地重用其提供的功能。您可以通过将其作为参数传递来访问函数中的外部变量。请参见下面的代码中的注释:

//Create your vars
var star_1 = document.querySelector('#star1');
var star_2 = document.querySelector('#star2');
var toggle = false;

//Define the function to accept a parameter (a star)
function favToggle(star) {
  if (toggle === true) {
    star.src = "assets/svg/checked-star.svg";
  } else {
    star.src = "assets/svg/unchecked-star.svg";
  }
  toggle = !toggle;

  //Log some info so we can see it's working as expected
  console.log(`${star.id} src property is now: ${star.src}`);
  console.log(`toggle is now: ${toggle}`);
}

//Add your event listeners by passing a reference to the star (this)
star_1.addEventListener("click", function() {
  favToggle(this);
});
star_2.addEventListener("click", function() {
  favToggle(this);
});
<div id="star1">star1</div>
<div id="star2">star2</div>