简体   繁体   English

显示而不重新加载页面javascript

[英]reveal without reloading page javascript

Is it possible to add a paragraph or line of text using a div onClick using javascript, without reloading the page? 是否可以使用javascript使用div onClick添加段落或文本行,而无需重新加载页面?

<a onclick="reveal">Click me!</a>
  <div id="vTitle">
      <!-- show text in this div -->
  </div>

<script type="text/javascript">
  if (onclick == "reveal"){
    var newListItem = document.createElement('p');
    var newListItemText = document.createTextNode('Vualà');
    newListItem.appendChild(newListItemText);
    var newListItemPosition = document.getElementById('vTitle');
    newListItemPosition.appendChild(newListItem);
    }
</script>

You can use jquery for dom manipulation. 您可以使用jquery进行dom操作。 Bellow is the jquery code and little modified hmtl. 波纹管是jQuery代码,几乎没有修改过的hmtl。

The jquery jQuery的

$(document).ready(function () {

        $("#reveal").on('click', function (e) {
            e.preventDefault();
            $("#vTitle").append("<p>Test</p>");
        });
 });

And Html is HTML是

<a id="reveal">Click me!</a>
<div id="vTitle">
    <!-- show text in this div -->
</div>

You have to first call an function in the onclik of a . 你必须首先调用一个函数在onclika Since its a tag, we will have to preventDefault so the page does not redirect in case you add a href to it. 由于它a标记,因此我们必须preventDefault以便在您向其添加href不会重定向页面。

Click me! 点击我!

Then in reveal function we write a simple code to show a line of text. 然后在reveal功能中,我们编写了一个简单的代码来显示一行文本。

<script type="text/javascript">
 function reveal(e) {
    e.preventDefault();
    var newListItem = document.createElement('p');
    var newListItemText = document.createTextNode('Vualà');
    newListItem.appendChild(newListItemText);
    var newListItemPosition = document.getElementById('vTitle');
    newListItemPosition.appendChild(newListItem);
 }
</script>

If you click multiple times, then multiple p tag will be added to the div . 如果单击多次,则多个p标签将添加到div

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM