我在 JS
中创建了一个函数,它通过 AJAX
获取 HTML
内容并将其放入 Bootstrap 对话框中。
现在我已经将 autofocus 属性添加到动态 HTML 中的输入框。问题是我在输入框上看到了一段时间的焦点,然后它就消失了。
JS代码:
function getPage(userid) {
$.ajax({
type: 'POST',
url: PAGE_URL,
data: {'userid':userid},
success: function (data) {
changeDialogContent(data);
},
error: function (e, textStatus) {
alert('Error occured while processing your request');
}
});
}
changeDialogContent
函数只是将动态内容作为 HTML 添加到对话框。
var bootstrapmodal=$('#modelDiv');
function changeDialogContent(content) {
bootstrapmodal.html(content);
}
输入的HTML代码:
<input type="text" class="form-control input-sm someInputBox" autofocus="autofocus" value="0" placeholder="Enter Name"/>
我也试过在将 HTML 内容设置到 Bootstrap 对话框之后添加 $('.someInputBox').focus();
,但也不走运。
我遗漏了什么重要的东西吗?
最佳答案
这是我认为与您的目标类似的 php 代码..
测试.php:
<?php
echo '<input id="my-input" type="text" class="form-control input-sm someInputBox" autofocus="autofocus" value="0" placeholder="Enter Name"/>';
?>
HTML 和 JAVASCRIPT 代码:
<html>
<head>
<script src = "bower_components/jquery/dist/jquery.js"></script>
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css">
<script>
function getPage() {
$.ajax({
type: 'POST',
url: "test.php",
data: {},
success: function (data) {
changeDialogContent(data);
document.getElementById("my-input").focus();
},
error: function (e, textStatus) {
alert('Error occured while processing your request');
}
});
}
function changeDialogContent(content) {
$('#modelDiv').html(content);
}
</script>
</head>
<body onload="getPage()">
<div id = "modelDiv" class="col-md-3 col-md-offset-4">
</div>
</body>
</html>
我用的是bower所以jquery和bootstrap的源码路径不是cdn。 而且这段代码工作得很好..我没有遇到任何错误。 很抱歉我无法提供 fiddle ,因为它有服务器请求和响应。所以我在自己的机器上测试了它。
如果我误解了什么,请纠正我。
关于javascript - 自动对焦在来自 AJAX 的动态内容的文本框中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37675318/