如何使用JavaScript使用多重重命名功能. [英] How to use multiple rename function using javascript.

查看:122
本文介绍了如何使用JavaScript使用多重重命名功能.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I''m new to Javascript and I''ve only recently learned HTML and CSS. So, example, in this example;
  <body>
    <p>Player 1: Chris</p>

    <script>
      var para = document.querySelector(''p'');
      para.addEventListener(''click'', updateName);
      function updateName() {
        var name = prompt(''Enter a new name'');
        para.textContent = ''Player 1: '' + name;
      }
    </script>

The given Javascript can only change "Player 1: Chris". If I have to add "Player 2: Adam" the same script doesn''t work. What modifications do I have to use?



我尝试过的事情:



What I have tried:

<body>
   <p>Player 1: Chris</p>

   <script>
     var para = document.querySelector(''p'');
     para.addEventListener(''click'', updateName);
     function updateName() {
       var name = prompt(''Enter a new name'');
       para.textContent = ''Player 1: '' + name;
     }
   </script>

推荐答案

您需要将ID添加到元素中并相应地选择
You need to add ID''s to the elemnts and select accordingly
<p id="p1">Player 1: Chris</p>
  <p id="p2">Player 2: Fred</p>

<script>
 var p1 = document.getElementById("p1");
 var p2 = document.getElementById("p2");
 p1.addEventListener('click', updateName1);
 p2.addEventListener('click', updateName2);
      function updateName1() {
        var name = prompt('Enter a new name');
        p1.textContent  = 'Player 1: ' + name;
      }	
      function updateName2() {
        var name = prompt('Enter a new name');
        p2.textContent  = 'Player 2: ' + name;
      }	
</script>

我敢肯定,您可以将两个侦听器功能合并为一个,并传递一个变量....

I''m sure with a little ingenuity you could combine the two listener functions into one and pass a variable....


事件处理程序将传递了一个事件对象,该对象公开了 currentTarget [
The event handler will be passed an event object, which exposes the currentTarget[^] property representing the element which raised the event.

The only problem is knowing which label to display in front of the name. But you can get around that by using another element to hold the name:
<p class="player">Player 1: <span class="name">Chris</span></p>
<p class="player">Player 2: <span class="name">Fred</span></p>

var para = document.querySelectorAll('p.player');
for (var i = 0; i < para.length; i++){
    para[i].addEventListener('click', updateName);
}

function updateName(e) {
    var p = e.currentTarget;
    var label = p.querySelector('span.name');
    var name = label.innerText;
    name = prompt('Enter a new name', name);
    if (name) {
        label.innerText = name;
    }
}

演示 [ ^ ]


这篇关于如何使用JavaScript使用多重重命名功能.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆