我正在尝试从输入文本字段中获取文本并将值放在表格行中,但每次有人发布的内容最旧的帖子向下移动1行时,这就是我的内容,但我现在非常困惑< / p>
<HTML>
<HEAD>
<SCRIPT Language="JavaScript">
<!--//
function thisPost(frm){
if (frm.postHere.value == "")
alert("Hey! You didn't enter anything!")
else
frm.postHere.value = ""
<table style="width:100%">
<tr>
<td>post + frm.postHere.value</th>
</tr>
</table>
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="thisPost">
<P>Post this: <INPUT TYPE="TEXT" NAME="postHere"><BR><BR>
<INPUT TYPE="Button" Value="Post" onClick="thisPost(this.form)">
</P>
</FORM>
</BODY>
</HTML>
答案 0 :(得分:0)
您的代码中存在许多语法错误,因此我不确定您是如何在当前状态下运行它的。此外,您的标记和方法相当过时。我强烈建议在像jQuery这样的跨浏览器DOM框架中投入时间,然后是一个好的前端MVW和模板框架。除此之外,我已将您的代码重新编写为更实用的表单。希望这会让你前进。
function thisPost(){
//Use getElementById to retrieve the DOM elements you're looking for
var txtPost = document.getElementById('txtPost');
var post = txtPost.value;
if (post == "") {
alert("Hey! You didn't enter anything!")
} else {
alert("The field contains the text: " + post);
//Get a reference to your table
var table = document.getElementById('posts');
//TODO: This is unsafe and subject to script injection.
//http://en.wikipedia.org/wiki/Code_injection#HTML_Script_Injection
table.innerHTML = '<tr><td>' + post + '</td></tr>' + table.innerHTML;
txtPost.value = "";
}
}
//from: http://stackoverflow.com/a/10150042/402706
// add event cross browser
function addEvent(elem, event, fn) {
if (elem.addEventListener) {
elem.addEventListener(event, fn, false);
} else {
elem.attachEvent("on" + event, function() {
// set the this pointer same as addEventListener when fn is called
return(fn.call(elem, window.event));
});
}
}
//Don't bind events in your HTML markup, instead bind them in JavaScript.
addEvent(document.getElementById('btnPost'), 'click', thisPost);
&#13;
table{
width:100%;
}
&#13;
<form name="thisPost">
<p>
Post this: <input type="Text" name="postHere" id='txtPost'>
<br/><br/>
<input type="Button" value="Post" id='btnPost'/>
</p>
<table id='posts'>
</table>
</form>
&#13;
答案 1 :(得分:0)
<label>Post this:</label>
<input type="text" name="postHere" />
<br />
<br />
<button>Post</button>
<table></table>
var btn = document.getElementsByTagName("button")[0];
var inpt = document.getElementsByName("postHere")[0];
var cnt = 0;
btn.onclick = function() {
if (!inpt.value) alert("Hey! You didn't enter anything!");
else alert("The field contains the text: " + inpt.value);
var tbl = document.getElementsByTagName("table")[0];
var row = tbl.insertRow(cnt++);
var cell = row.insertCell(0);
var txt = document.createTextNode(inpt.value);
cell.appendChild(txt);
};