当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Add new text to div every time button is clicked

问题描述:

I've been looking into AngularJS a bit, and I want to know it there's a way - without making the page refresh, to keep adding more text to a div every time the button is pressed, using AngularJS? I know this can be done with text and submit buttons, but I don't know how it can be done with just buttons, here's an example.

<button>Word</button> <!-- Every time this is clicked, add 'word' to the div 'text' without refreshing -->

<div id="text" class="text">

<!-- Write word here as many times as the button is pressed -->

</div>

https://jsfiddle.net/kgmw5rqp/

网友答案:

Using AngularJS your can do it using ng-model with ng-repeat

FIDDLE

var myApp = angular.module('myApp',[]);

myApp.controller('myCtrl', function($scope) {
    $scope.data = {
        texts : []
    }

    $scope.addText = function(text){
        $scope.data.texts.push(text)
    }   
});

<div ng-controller="myCtrl">
    <button ng-click="addText(data.text)">Add text</button>
    <input type="text" ng-model="data.text">
    <div ng-repeat="text in data.texts">{{text}}</div>
</div>
网友答案:

See this fiddle

You can do this using pure JavaScript. Please see the below JS

function addWord() {
  document.getElementById("text").innerHTML = document.getElementById("text").innerHTML + "word";
}

Invoke the function addWord() by setting the onclick of the button as follows

<button onclick="addWord()">Word</button>
分享给朋友:
您可能感兴趣的文章:
随机阅读: