[英]Trouble creating elements with JQuery
I have this form: 我有这个表格:
<form>
<input id="checkuser" type="text" name="user" placeholder="Your username"/>
</form>
And what I'm doing with JQuery is to check if the username that was written is avalible. 我正在使用JQuery来检查所写的用户名是否可用。 This is the JQuery code:
这是JQuery代码:
$('#checkuser').click(function (){
$(this).change(function () {
$.ajax( {
url: '/check',
type: 'POST',
cache: false,
data: { checkuser: $(this).val() },
dataType: "json",
complete: function() {
},
success: function(data) {
var check = JSON.stringify(data.aval);
if (check == "false") {
$('<p>Not available.</p>').insertAfter('#checkuser');
}
else {
$('<p> Available!</p>').insertAfter('#checkuser');
}
},
error: function() {
console.log('process error');
}
});
});
});
The problem is: if the user is not available, the user has to rewrite the username and when jQuery recheck if is available, instead of rewrite the content of <p>
, JQuery create another <p>
next to the old <p>
, ergo, this is the result: Not available.Available!
的问题是:如果用户是不可用,则用户必须重写的用户名和当jQuery的重新检查,如果是可用的,而不是重写的内容
<p>
,JQuery的创建另一个<p>
旁边的老<p>
因此,结果如下: Not available.Available!
, instead write only one of them. ,而只写其中之一。 How can I resolve this?
我该如何解决?
To solve this I would add a blank <p></p>
tag after the input and update this tag when needed. 为了解决这个问题,我将在输入之后添加一个空白的
<p></p>
标记,并在需要时更新该标记。
<form>
<input id="checkuser" type="text" name="user" placeholder="Your username"/>
<p></p>
</form>
$('form p').text('Available!');
insertAfter
will append new html context to the div. insertAfter
会将新的html上下文附加到div。 instead create another div after the checkuser
div and replace the html inside: 而是在
checkuser
div之后创建另一个div并替换其中的html:
<input id="checkuser" type="text" name="user" placeholder="Your username"/>
<div id="msg"></div>
and then just: 然后:
$('#msg').text('your text if available or not here');
The insertAfter() method is working as designed: it finds the element ( #checkuser in this case) and appends a new paragraph after it. insertAfter()方法按设计方式工作:它找到元素(在这种情况下为#checkuser ),并在其后追加一个新段落。
You probably need to create a DIV or SPAN element after your INPUT tag like this: 您可能需要在INPUT标记之后创建DIV或SPAN元素,如下所示:
<span id="checkuser-validation"></span>
Then adapt your JavaScript code to look like this: 然后修改您的JavaScript代码,如下所示:
if (check == "false") {
$('#checkuser-validation').Empty();
$('#checkuser-validation').Html('Not Available');
}
... and so on. ... 等等。 Hope that helps :)
希望有帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.