doufu7464 2018-09-19 06:12
浏览 47
已采纳

分别更改div的内容

I'm trying to add some content inside my divs on hover, but not the CSS way.

function hover(description){
  console.log(description);
  document.getElementById('first-item').innerHTML = description;
  document.getElementById('second-item').innerHTML = description;
}
.slide {
  background: blue;
  width: 200px;
  height: 200px;
  float: left;
  margin: 10px;
}
<?php
  $content = "some text";
?>

<div>
  <div>
    <div class="slide" id="first-item" onmouseover="hover('<?php echo $content; ?>')" onmouseout="hover('')"></div>
    <div class="slide" id="second-item" onmouseover="hover('<?php echo $content; ?>')" onmouseout="hover('')"></div>
    <div class="slide" id="third-item"></div>
  </div>
</div>

I want only the content of the .first-item to change when I hover it and only the content of the .second-item to change when I hover it. But as you can see when I hover either one, the content of both changes.

What did I do wrong?

</div>
  • 写回答

4条回答 默认 最新

  • doushang2023 2018-09-19 06:21
    关注

    You can pass this as a element reference in hover function for both mouse in and mouse out so that you can then use this reference in JavaScript to set innerHTML of that particular element:

    function hover(elem, description) {
      elem.innerHTML = description;
    }
    .slide {
      background: blue;
      width: 200px;
      height: 200px;
      float: left;
      margin: 10px;
    }
    <div>
        <div>
          <div class="slide" id="first-item" onmouseover="hover(this, 'sampleText')" onmouseout="hover(this, '')"></div>
          <div class="slide" id="second-item" onmouseover="hover(this, 'sampleText')" onmouseout="hover(this, '')"></div>
          <div class="slide" id="third-item" onmouseover="hover(this, 'sampleText')" onmouseout="hover(this, '')"></div>
        </div>
      </div>

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable