[英]jQuery, appending HTML string not working
When using the code below I am unable to add the HTML string to the innerHTML of the target HTMLElement. 使用下面的代码时,我无法将HTML字符串添加到目标HTMLElement的innerHTML中。 What am I doing wrong? 我究竟做错了什么? Is there a better way to do this? 有一个更好的方法吗?
<html>
<head>
<title>Add HTML input with jQuery</title>
<!--
* This code is meant to include the jQuery library v.1.9.1
* from Google API
-->
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js' type='text/javascript'></script>
<script>
$('document').ready(function(){
$('#add').click(function(){
var src = $('#src'); // alert(src);
var trgt = $('#src'); // alert(trgt);
var x = null;
var child = null;
var str = null;
if(null != src.val()){
alert(1);
x = trgt.children().length;
str = '<input type="text" name="array[]" id="index' + x + '" value="' + src.val() + '" />';
trgt.html().append(str);
src.val() = null;
}else{
alert('src value is emppty');
}
});
});
</script>
</head>
<body>
<div id="box">
<label></label> <input type="text" name="src" id="src" value="" /> <button id="add">+</button>
<div id="trgt">
</div>
</div>
</body>
</html>
var trgt = $('#src');
... Your source and target selectors are the same. ...您的源和目标选择器是相同的。
This var trgt = $('#trgt')
is not the only problem I noticed. 这个var trgt = $('#trgt')
不是我注意到的唯一问题。
There is trgt.html().append(str);
有trgt.html().append(str);
which should be trgt.append(str);
应该是trgt.append(str);
. 。
And then src.val() = null;
然后src.val() = null;
, are you trying to reset the <input>
value? ,你想重置<input>
值吗? You can simply do it with src.val('');
您可以使用src.val('');
来完成它src.val('');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.