Delete text between <p> by javascript
I have the following HTML,two buttons and a paragraph code, and javascript, like the following:
// HTML
<input type="button" onclick="insert()" value="insert"开发者_JS百科/>
<input type="button" onclick="delete()" value="delete"/>
<p id='text'>
Line 1
Line 2
</p>
//javascript
function insert(){
// ?
}
function delete(){
// ?
}
When the user clicks the delete button, the Line 1 and Line 2 will be deleted.
When the user clicks the insert button, the Line 1 and Line 2 will be inserted.
The Line 1 and Line 2 will be only insert when they are not between the <p id='text'>
.
Can anyone help me?
For insert()
, how about
document.getElementById('text').innerHTML = 'Line 1\nLine 2';
and for delete()
, how about
document.getElementById('text').innerHTML = '';
Please note that delete
is a JavaScript keyword (and it's even actually implemented, which is more than I can say for the utterly excessive amount of reserved keywords that JavaScript has). You will need to name your delete()
function something else.
With jQuery you can try:
$("#text").text('');
You could something quick and easy with jQuery... adding id
s to your buttons
.
$('#delete').click(function(){
$('#text').html('');
})
$('#insert').click(function(){
$('#text').html('Line 1 Line 2');
})
http://jsfiddle.net/jasongennaro/MTJxH/1/
function insert() {
var para = document.getElementById("text");
if(para.innerHTML === "") {
para.innerHTML = "line1<br />line2";
}
}
function remove() {
document.getElementById("text").innerHTML = "";
}
However, please notice that I've changed the name of your delete
function, because delete
is a JavaScript keyword, and can't be used as the name of a function.
Here's a working example.
function insert() {
var p = document.getElementById('text');
if (p.innerHTML == '') {
p.innerHTML = 'Line 1<br />Line 2';
}
}
function delete() {
document.getElementById('text').innerHTML = '';
}
function delete(){
$('#text').html('');
}
function insert(){
if($('#text').text()=="")// add only if nothing inside
{
$('#text').html('Line 1 Line 2');
}
}
function delete()
{
var delMe = document.getElementById('text');
delMe.innerHTML = '';
}
function insert()
{
var insMe = document.getElementById('text');
insMe.innerHTML = "Line 1\r\nLine2";
}
Easy peasy.
精彩评论