将多个元素上的一个属性的值传递给另一个属性

Carry values from an attribute on multiple elements to another attribute

我有这个JavaScript检测浏览器是否支持触摸事件,然后为每个有点击事件的元素设置一个触摸事件:

function isTouchEnabled() {
    if ('ontouchstart' in window) {
    var all = document.querySelectorAll('[onclick]');
        for (var i = 0; i < all.length; i++) {
            all[i].setAttribute('ontouchstart', car);
            var car = all[i].getAttribute('onclick');
        }
    }
}

一直到这个位:all[i].setAttribute('ontouchstart', car);

这个位,我的目的是把click事件的属性值传给touch事件,但是不行,因为touch事件的属性值最终是undefined。谁能解决这个问题?

试试这个:

function hitMe() {
    alert('I am hit !');
}
function isTouchEnabled() {
  if ('ontouchstart' in window) {
    var all = document.querySelectorAll('[onclick]');
    for (var i = 0; i < all.length; i++) {
      var car = all[i].getAttribute('onclick');
      all[i].setAttribute('ontouchstart', car);
    }
  }
}
isTouchEnabled();
<div onclick="hitMe()">Click Me!</div>