繁体   English   中英

将innerhtml javascript转换为jquery

[英]converting innerhtml javascript to jquery

我正在学习jQuery,所以我一直在逐步浏览旧代码,尝试更改所有内容,到目前为止,这很容易,直到遇到此问题为止。

我有这段JavaScript代码

myText.innerHTML += "<li>"+input_text+" "+input_date+" "+input_time+"</li>";}

使用这段HTML代码

<button onClick='buttonClicked'>Submit!</button>

我以为我会转换成

<input type ="button" id ='buttonClicked' value="Submit!"/>

我似乎还没有完全正确地使用jQuery,并且它有点令人沮丧。

显然,除了我提供的代码之外,还有更多其他功能,我只是想让所有人都专注于它,如果您真的需要更多,请问一下,我已经将其余的js转换为jQuery。 我的朋友说我应该使用“附加”,但到目前为止,我还没有弄清楚。

您可以将其转换为我,然后将其链接至一些文档以了解其工作原理吗? 让我知道,这对加快我对这些东西的理解会非常有帮助,谢谢!

编辑:是

function buttonClicked() {
var myText = document.getElementById('myText');
var input_text = document.getElementById('input_text').value  ; 
var input_date = document.getElementById('input_date').value  ;        
var  input_time = document.getElementById('input_time').value  ; 
myText.innerHTML += "<li>"+input_text+" "+input_date+" "+input_time+"</li>";}

到目前为止,jQuery是:

$(document).ready(function() {
var input_text = $('#input_text').val();   
var input_date = $('#input_date').val();
var input_time = $('#input_time').val();
$('#buttonClicked').click(function(){
  //$('#myText').append(function(){ $("<li> "+input_text+" "+input_date+" "+input_time+" </li>") 
//$('myText').html();

});


});

我已经尝试了很多,但不确定从哪里开始。

假设您在HTML上有类似的内容:

<input type="button" id="buttonClicked" value="Submit!">
<div id="myText></div>

您可以像这样使用jQuery:

$('#buttonClicked').click(function () {
    $('#myText').append("<li>"+input_text+" "+input_date+" "+input_time+"</li>");
});

第一步是使用JQuery将单击处理程序添加到您的按钮。 文件。

$("#buttonClicked").click(function() {
  //handle click
});

您需要在点击处理程序正在调用的函数中使用append方法。 可以在此处找到该文档。

将单击处理程序添加到您的按钮,然后使用$.append插入所需的内容。

您可以在此处查看文档: http : //api.jquery.com/append/

$(function(){
   $('#buttonClicked').click(function(){
      var input_text = $('#input_text').val();
      var input_date = $('#input_date').val();
      var input_time = $('#input_time').val();
      $('#myText').append("<li>"+input_text+" "+input_date+" "+input_time+"</li>");
   });

});

其他答案是有效的,但我建议对点击事件使用“ on”:

$("#buttonClicked").on("click", function(e){
    e.preventDefault(); //this, along with return false, will prevent default behavior from button clicks - probably only useful in web applications, but a good convention to start using
    $('#myText').append("<li>"+input_text+" "+input_date+" "+input_time+"</li>"); // Note that this will continue to append additional li elements with each button click.  If that is not desired, you can call $("#myText").empty(); before adding the li element
    return false;
});

暂无
暂无

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

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