我对HTML、JavaScript和Jquery都是新手。我似乎弄不明白为什么Append()在我调用Val("")之后不再向TextArea追加文本。之所以需要调用Val(""),是因为我想在每次开始搜索时清除TextArea中的文本。因此,在UI上,我会输入游戏或公司的名称文本,然后按下按钮,根据输入字段搜索游戏。下面是我使用的来自site.js的代码。谢谢。
var arr = [
{
Game:"Double Dragon",
Developer: "Technos Japan Corp",
Publisher: "Acclaim",
Platform: {
Console: "Nintendo"
}
},{
Game:"Street Fighter 2000",
Developer: "Capcom",
Publisher: "Capcom",
Platform: {
Console: "Nintendo"
}
},{
Game:"Super Mario Bros.",
Developer: "Nintendo",
Publisher: "Nintendo",
Platform: {
Console: "Nintendo"
}
},{
Game:"Secret Mana",
Developer: "SquareSoft",
Publisher: "SquareSoft",
Platform: {
Console: "Super Nintendo"
}
},{
Game:"Final Fight",
Developer: "Capcom",
Publisher: "Capcom",
Platform: {
Console: "Super Nintendo"
}
},{
Game:"Super Contra",
Developer: "Konami",
Publisher: "Konami",
Platform: {
Console: "Nintendo"
}
},{
Game:"Mega Man",
Developer: "Capcom",
Publisher: "Capcom",
Platform: {
Console: "Nintendo"
}
}
];
function GameBtnEvent()
{
//$("#textAreaText").val('');//if I comment this out, Append() call will work, otherwise Append() does not append text to TextArea
DisplayResults();
}
function DisplayResults()
{
var found = 0;
$.each(arr, function (index, value) {
var gameName = $("#searchTitle").val();
var companyName = $("#selectionBlock").val();
if(companyName.toLowerCase() == value.Publisher.toLowerCase())
{
$('#textAreaText').append("Title: " + value.Game + "\n");
$('#textAreaText').append("Company: " + value.Publisher + "\n");
$('#textAreaText').append("Console: " + value.Platform.Console + "\n\n");
found = 1;
}
else if(companyName.toLowerCase() == value.Publisher.toLowerCase() &&
gameName.toLowerCase() == value.game.toLowerCase() )
{
$('#textAreaText').append("Title: " + value.Game + "\n");
$('#textAreaText').append("Company: " + value.Publisher + "\n");
$('#textAreaText').append("Console: " + value.Platform.Console + "\n\n");
found = 1;
}
});
if(found == 0)
{
$("#textAreaText").append("game not found");
}
}更新:这种行为似乎只发生在Chrome上,但Explorer没有问题。
发布于 2017-12-30 08:06:18
假设#textAreaText是一个<textarea>元素,那么您从一开始就不应该使用append()。在所有情况下都使用val()。如果您需要追加现有值,请向val()提供一个函数,该函数接受当前值作为参数,您可以在返回新值时使用该参数,如下所示:
function GameBtnEvent() {
$("#textAreaText").val('');
DisplayResults();
}
function DisplayResults() {
$.each(arr, function(index, value) {
if ($("#selectionBlock").val().toLowerCase() == value.Publisher.toLowerCase() || $("#searchTitle").val().toLowerCase() == value.game.toLowerCase()) {
$('#textAreaText').val(function(i, v) {
return `${v}Title: ${value.Game}\nCompany: ${value.Publisher}\nConsole: ${value.Platform.Console}\n\n`);
});
}
});
if (arr.length == 0) {
$("#textAreaText").val("game not found");
}
}还请注意,我使逻辑更简洁,因为您的两个条件几乎相同,您只需在OR语句中使用AND逻辑。
https://stackoverflow.com/questions/48029633
复制相似问题