【问题标题】:javascript, on click change the html of an element different than the one that was clicked onjavascript,单击时更改与单击的元素不同的元素的html
【发布时间】:2021-02-14 02:17:57
【问题描述】:

我试图通过单击一个单词来更改 p 标签的 innerhtml,但我不想更改我单击的单词的 innerhtml。我想更改我单击的单词旁边显示的单词。

我的 html 看起来像这样。单击的单词的每个 id 后跟一个黑色的 p 标签,其 id 比单击的那个多一个

<p id="word0" data-index=0 class="russian"> люблю</p>
<p id="word1" data-index=1 class="english"></p>

当我点击俄语单词时,英语单词的黑色p标签应该由英语单词填写。

这是我的 javascript。暂时将单词一二三等,单击时将放置在俄语单词旁边。有没有一种方法可以将标签的 innerHTML 定位到被点击的单词旁边?

<script>

    let allWordsList = {'word0':'one','word1':'one','word2':'two','word3':'three'}


    function changeText(e){
        var number = e.target.id;

       // Set the text to the data-index value of the HTML element:
       e.target.innerHTML = allWordsList[number];

    }

</script>

【问题讨论】:

标签: javascript innerhtml word


【解决方案1】:

您正在更改被点击元素的 innerHTML。 e 是您单击的段落的事件,e.target 是您单击的 HTML 元素。所以如果你改变e.target的innerHTML,那么它会改变它自己而不是它的下一个兄弟。

e.target.innerHTML = allWordsList[number];

解决这个问题的一种方法是:

let allWordsList = {
  'word0': 'one',
  'word1': 'one',
  'word2': 'two',
  'word3': 'three'
}


function changeText(e) {
  var number = e.target.id;
  var convertedNumber = allWordsList[ number ];
  //Set the text to the data-index value of the HTML element:
  const nextSibling = e.target.nextElementSibling;
  nextSibling.innerHTML = convertedNumber;
}

const paragraphs = document.querySelectorAll(".para");
paragraphs.forEach( e => {
  e.addEventListener("click", changeText);
})
<p id="word0" data-index=0 class="russian para"> люблю</p>
<p id="word1" data-index=1 class="english"></p>

<p id="word2" data-index=0 class="russian para"> люблю</p>
<p id="word3" data-index=1 class="english"></p>

【讨论】:

  • 奇迹。做得好!这立即对我有用。我只是复制并粘贴了它!
猜你喜欢
  • 1970-01-01
  • 2016-09-11
  • 2016-01-12
  • 1970-01-01
  • 1970-01-01
  • 2017-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多