我有一个使用 jQuery 的网页,它有几个输入框。输入框设置为在 click() 事件触发时自动选择现有文本(值属性)。在我尝试从文档 ready() 事件中预填充其中一个输入框之前,它一直运行良好。如果我这样做,那么尽管在所需字段上调用了 focus() 方法,但该字段不会获得焦点(光标不在输入框中并且文本不会自动选择)。如果我单击该字段,则文本会自动选择,以便该部分仍然有效,只是没有设置焦点。
我已经包含了整个文档就绪事件的 Javascript 代码,以防页面上的元素之间产生不好的协同作用。请注意,getSearchArguments() 调用只是获取 URL 参数并将它们转换为关联数组。这是我尝试自动聚焦/选择的电子邮件地址字段的 HTML:
<!-- E-mail Address -->
<div NAME="divEmailAddress" ID="divEmailAddress">
<img NAME="imgEvernoteEmailAddress" ID="imgEvernoteEmailAddress" src="/images/evernote-mail-address.png" align="left" />
<input type="text" NAME="emailAddress" ID="emailAddress" wrap="soft" style="margin-left:5px;width:600px;" title="Enter your Evernote E-mail address here" value="Enter your E-mail address" ></input>
</div>
谁能告诉我如何解决这个问题,以便在预填充输入框后 focus() 方法仍然有效?
更新:事实证明,在 focus() 调用解决了问题之后,添加了对 select() 的新显式调用。如果有人能告诉我为什么会这样,我将不胜感激。
$(document).ready
(
function()
{
// Put jQuery related initialization code that must occur after the document is ready here.
// Have all the edit boxes except the Tags edit box auto-select the current text upon entry.
$("#editEvernoteTags").autoSuggest
(
data.items,
{
selectedItemProp: "name",
searchObjProps: "name",
startText: "Enter Evernote tags here...",
/* See autoSuggest.css
open: function(event, ui)
{
$(this).autoSuggest("widget").css
(
{
"width": 200
}
);
}
*/
} // data. items
); // $("input[type=text]").autoSuggest
$("#emailAddress").onblur = checkEmailAddress;
// $("#emailAddress").css('width', $("#editEvernoteTags").css('width') * 2);
// Synchronize the control widths to the autoSuggest "as-selections" class element.
var tagsWidth = $("ul.as-selections").width();
$("#emailAddress").width(tagsWidth);
$("#editComment").width(tagsWidth);
// If an E-mail address was provided as a URL argument, put it in the E-mail address field.
var urlEmailAddress = getSearchArguments().emailAddress;
// >>> COMMENTING OUT THIS IF/ELSE BLOCK ALLOWS THE FOCUS() METHOD TO WORK.
// value="Enter your E-mail address"
if (urlEmailAddress)
$("#emailAddress").val(urlEmailAddress);
else
$("#emailAddress").val("Enter your E-mail address");
// E-mail address
$('#emailAddress').click(function()
{
$(this).select();
});
// Comment
$('#editComment').click(function()
{
$(this).select();
});
// Set focus to the E-mail field.
$("#emailAddress").focus();
// >>>> This is needed to initially select the text the first time
// if the pre-fill code above is used.
$("#emailAddress").select();
} // function()
); // $(document).ready