onclick添加事件问题

先在这记录一下问题哈

明明可以这样
<button οnclick="displayDate()">点我</button>
却为什么要这样啊-->通过class获取button 赋予onclick

今天(190711)我找到原因了!

具体原因是:便于维护、将您的编程逻辑与内容分离也会使您的站点对搜索引擎更加友好。

具体博客说明:https://blog.csdn.net/ifnotcorrect/article/details/95505428


      //以下是通过class获取 button 赋予 onclick事件属性

      1. 按钮
      <button class="randomize">随机生成笑话</button>
      
      2. 获取按钮
      const randomize = document.querySelector('.randomize');
      
      3. 给按钮添加事件监听
      randomize.addEventListener('click', result);
      
      4. 监听函数
      function result() {
  let newStory, xItem, yItem, zItem, name;
  if (document.getElementById('cn').checked) {
    newStory = storyTextZh;
 
    xItem = randomValueFromArray(insertA);
    yItem = randomValueFromArray(insertB);
    zItem = randomValueFromArray(insertC);

    newStory = newStory.replace(':inserta:', xItem);
    newStory = newStory.replace(':inserta:', xItem);
    newStory = newStory.replace(':insertb:', yItem);
    newStory = newStory.replace(':insertc:', zItem);

    if (customName.value !== '') {
      name = customName.value;
      newStory = newStory.replace('李雷', name);
    }
  } else {
    newStory = storyText;

    xItem = randomValueFromArray(insertX);
    yItem = randomValueFromArray(insertY);
    zItem = randomValueFromArray(insertZ);

    newStory = newStory.replace(':insertx:', xItem);
    newStory = newStory.replace(':insertx:', xItem);
    newStory = newStory.replace(':inserty:', yItem);
    newStory = newStory.replace(':insertz:', zItem);

    if (customName.value !== '') {
      name = customName.value;
      newStory = newStory.replace('Bob', name);
    }

    if (document.getElementById("uk").checked) {
      const weight = Math.round(300 * 0.0714286) + ' stone';
      const temperature = Math.round((94 - 32) * 5 / 9) + ' centigrade';
      newStory = newStory.replace('94 fahrenheit', temperature);
      newStory = newStory.replace('300 pounds', weight);
    }
  }

  story.textContent = newStory;
  story.style.visibility = 'visible';
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值