【问题标题】:Dynamically assign an onclick event to links inside a for loop. **Native Javascript Only**将 onclick 事件动态分配给 for 循环内的链接。 **仅限本机 Javascript**
【发布时间】:2017-09-18 18:53:09
【问题描述】:

我正在学习 Javascript 入门课程,我正在做的任务是通过单击“阅读更多”链接来扩展文本,将链接更改为“阅读更少”,并在单击“时缩小文本”少读'链接。我已经差不多完成了,但我有一个问题。包含文本的整个 div 是“onclick”元素,而不是链接。意思是,我在 div 内单击的任何地方都会激活 onclick 事件。如何将 onclick 事件分配给链接而不是整个 div?

this.oData = {};

function getData(){
 //mimic ajax request
 return [
   {
     blogID: 0,
     blurb: "blurb 1 sfdasf safs fdsaf asdf asdfa sdf asdf asdf asdfa sdfasd fasdf asdf asdf asdf asdfasdfadsfadsfasdf asdf asdf sdfasd fasd fasdf asdf sadf asdfa sf"
   },
   {
     blogID: 1,
     blurb: "blurb 2 sfdasf safs fdsaf asdf asdfa sdf asdf asdf asdfa sdfasd fasdf asdf asdf asdf asdfasdfadsfadsfasdf asdf asdf sdfasd fasd fasdf asdf sadf asdfa sf"
   },
   {
     blogID: 2,
     blurb: "blurb 3 sfdasf safs fdsaf asdf asdfa sdf asdf asdf asdfa sdfasd fasdf asdf asdf asdf asdfasdfadsfadsfasdf asdf asdf sdfasd fasd fasdf asdf sadf asdfa sf"
   },
   {
     blogID: 3,
     blurb: "blurb 4 sfdasf safs fdsaf asdf asdfa sdf asdf asdf asdfa sdfasd fasdf asdf asdf asdf asdfasdfadsfadsfasdf asdf asdf sdfasd fasd fasdf asdf sadf asdfa sf"
   }
 ];
};

this.oData = getData();

(function injectInitial(){                                      //self-invoking function to inject the initial text into the HTML.
  for(var i=0; i < this.oData.length; i++){
    document.getElementsByTagName("div")[i].innerHTML = this.oData[i].blurb + "...<a href=\"javascript:void(0);\" >Read Less</a>";
    var activeBlurb = document.getElementsByTagName("div")[i];  //set activeBlurb to the div that the for loop is currently on [i]
    activeBlurb.id='blog' + this.oData[i].blogID;               //set the ID for the current div [i], like blog0, blog1, blog2, blog3
    activeBlurb.data = activeBlurb.id;
    // activeBlurb.data = activeBlurb.getElementsByTagName("a");   //set the data attribute of the current div to the info I need to pass(ID of the current div)
    console.log(activeBlurb.data);
    // // console.log(activeBlurb.getElementsByTagName("a"));
    activeBlurb.onclick = function(){                           //set the onclick event to send the ID of the current div(held in this.data) to function toggleMore.
      toggleMore(this.data);
    }
  }
})();

function toggleMore(clicked_id){
  console.log(clicked_id);

  var clickedBlurb = document.getElementById(clicked_id).innerHTML;
  var status = new Boolean(false);
  var snippet = clickedBlurb.slice(-8,-4);

  if (snippet=="Less") {
    status = 'true';
  } else {
    status = 'false';
  }
  injectText(status,clicked_id);
}

function injectText(status, clicked_id) {
    var intHalved;
    var halvedText = "";
    var fullText = "";
    var i = clicked_id.slice(-1);
    fullText = this.oData[i].blurb;
    intHalved = this.oData[i].blurb.length/2;
    halvedText = this.oData[i].blurb.slice(0,intHalved);

    if(status == 'true') { //this is set by the toggleMore function.
      //inject the shortenend text into the innerHTML
      document.getElementsByTagName("div")[i].innerHTML = (halvedText + "...<a href=\"javascript:void(0);\">Read More</a>");
    } else {
      //inject the full-length text into the innerHTML
      document.getElementsByTagName("div")[i].innerHTML = (fullText + "...<a href=\"javascript:void(0);\">Read Less</a>");
    }

    var activeBlurb = document.getElementsByTagName("div")[i];
    activeBlurb.data = activeBlurb.id;                       //set the data attribute of the current div to the info I need to pass(ID of the current div)
    activeBlurb.onclick = function(){                        //set the onclick event to send the ID of the current div(held in this.data) to function toggleMore.
      toggleMore(this.data);
    }
}

【问题讨论】:

    标签: javascript loops for-loop hyperlink assign


    【解决方案1】:

    使用委托可以检查目标是否为列表:

    div.addEventListener('click', (e) => if(e.target.matches('li')){...});
    

    【讨论】:

    • 我不明白你的意思。我将如何实现这种方法?
    • 你不需要 for 循环来遍历 div。您可以使用事件委托并在事件匹配所需元素时采取行动。看here
    • @dlindner999 您向 div 添加了一个事件侦听器,该事件侦听器在单击时触发,但您的函数不会运行,除非在该标记中专门单击 li 标记。 davidwalsh.name/event-delegate
    • @zfrisch 谢谢。我就是这个意思。
    • 所以在我的情况下会是:activeBlurb.addEventListener("click", function(e){ if (e.target.matches ("a")) { activeBlurb.onclick = function() { //设置onclick事件将当前div的ID(保存在this.data中)发送给函数toggleMore.toggleMore(this.data); } } }); ?我试过了,但没有用。 codepen.io/dlindner999/pen/NjrWvV?editors=1011
    猜你喜欢
    • 2011-06-29
    • 2020-08-31
    • 1970-01-01
    • 2013-03-29
    • 2017-10-16
    • 1970-01-01
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多