如何制作一个会改变网站上的文字的javascript?

时间:2016-11-16 22:24:00

标签: javascript jquery html

我有类似的东西

<html>

<body>
<h> Hello everybody, what's up? </h>
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Cras ex arcu,consequat sit amet volutpat vitae, finibus vel massa.  
    Sed eleifend quis justo eu auctor.
</p>
    Swap from:<br>
    <input type="text" name="from"><br>
    Swap to:<br>
    <input type="text" name="to"><br><br>
    <input type="submit" value="DO IT!">
</body>

</html>

我想添加一个脚本,将我在'交换'文本框中给出的单词更改为我在'交换到'文本框中给出的另一个单词,并出现在Lorem ipsum文本中。< / p>

我知道应该有类似的东西:

<button onclick="replaceText()">Click me!</button>

和一些javascript来从'Swap from'和'Swap to'中获取值,但我无法弄明白。

4 个答案:

答案 0 :(得分:1)

您只需将此功能添加到您的代码中即可。

function replaceText(){
    var text, swapFrom, swapTo, editedText;
    swapFrom = document.getElementsByName("from")[0].value;
    swapTo = document.getElementsByName("to")[0].value;
    editedText = document.getElementsByTagName('p')[0].innerHTML.replace(RegExp(swapFrom, "g"),swapTo);
    document.getElementsByTagName('p')[0].innerHTML = editedText;
}

答案 1 :(得分:0)

试试这个:

$('button').click(function()
{
   var fromValue = $('input[name=from]').val();
   var toValue = $('input[name=to]').val();
   var newText = $('p').text().replace(fromValue,toValue);
   $('p').text(newText);

});

示例:https://jsfiddle.net/18xagg6s/1/

答案 2 :(得分:0)

你想要实施的是什么?这是纯Javascript,没有jQuery:https://jsfiddle.net/hr28xr6p/

和一个片段:

&#13;
&#13;
replaceText.onclick = function replacer () {
  var from = document.getElementById('from').value;
  document.getElementById('to').value = from;
}
&#13;
<h> Hello everybody, what's up? </h>
<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Cras ex arcu,consequat sit amet volutpat vitae, finibus vel massa.  
    Sed eleifend quis justo eu auctor.
</p>
    Swap from:<br>
    <input type="text" name="from" id="from"><br>
    Swap to:<br>
    <input type="text" name="to" id="to"><br><br>
    <input type="button" value="DO IT!" id="replaceText">
&#13;
&#13;
&#13;

答案 3 :(得分:0)

没有jQuery,纯JavaScript。享受。

function swap() {
  var first = document.getElementById('from').value;
  var text = document.getElementById('text');
  var second = document.getElementById('to').value;

  text.innerHTML = text.innerHTML.replace(new RegExp(first, 'g'), second);
}
button {
  height: 30px;
  width: 100px;
}
<h>Hello everybody, what's up?</h>
  <p id='text'>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras ex arcu,consequat sit amet volutpat vitae, finibus vel massa. Sed eleifend quis justo eu auctor.
  </p>
  Swap from:
  <br>
  <input id='from' type="text" name="from">
  <br>Swap to:
  <br>
  <input id='to' type="text" name="to">
  <br>
  <br>
  <button onclick="swap()" type="submit" value="DO IT!">Do it!</button>