我已经使用Yandex API创建了SPA Translator应用程序。我刚刚完成了我应用程序的逻辑和功能,但是当用户从输入文本区域中删除所有文本时,我仍然停留在如何删除输出文本区域中的结尾字母上。
在用户删除了所有输入文本后,如何编写一种函数将输出文本区域清除回('')空白字符串。 (https://translex-app-shanemuir.c9users.io/dist/index.html)链接到我的实时网站。
这里我有一个HTML表单:
<div class="container myForm text-center">
<div class="row row-center">
<div class="col-sm-12">
<form class="form-inline well justify-content-center">
<textarea id="inputText" class="form-control" placeholder="Enter a Word..."></textarea>
<select class="form-control" id="selectLang">
<option selected>Choose Language...</option>
</select>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<h2 class="translation-header">Translation</h2>
<form class="form-inline well justify-content-center">
<textarea readonly class="form-control" placeholder="Translation" id="translation"></textarea>
</form>
</div>
</div>
</div>
这里有一些JS:
let searchInput = document.querySelector('#inputText');
let select = document.querySelector('#selectLang');
let textArea = document.querySelector('#translation');
let selectedLang = 'es';
function getLanguages(){
axios.get('https://translate.yandex.net/api/v1.5/tr.json/getLangs?key=trnsl.1.1.20180914T205319Z.b0ffef87e97badd3.e78787ec8a392b9772f8b8f56933b1d86463d330&ui=en')
.then((response) => {
let languages = response.data.langs;
let languageCode = {
name:'',
code:''
};
for(language in languages) {
languageCode.name = languages[language];
languageCode.code = language;
let option = document.createElement('option');
option.innerHTML = languageCode.name;
option.value = languageCode.code;
select.appendChild(option);
}
})
.catch((err) => {
console.log(err);
});
}
function translateText(textArg){
let searchText;
if(textArg == ''){
searchText = document.querySelector('#inputText').value;
}
else{
searchText = textArg;
}
if(searchText != ''){
axios.get('https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20180914T205319Z.b0ffef87e97badd3.e78787ec8a392b9772f8b8f56933b1d86463d330&lang=' + selectedLang + '&text=' + searchText)
.then((response) => {
let translateInput = document.querySelector('#translation');
translateInput.value = response.data.text[0];
})
.catch((err) => {
console.log(err);
});
}
}
searchInput.addEventListener('keyup',() => {
translateText('');
});
select.addEventListener('change',() => {
selectedLang = select.options[select.selectedIndex].value;
translateText('');
});
getLanguages();
答案 0 :(得分:1)
在else
上添加if
子句,以清空文本区域。
if(searchText != ''){
axios.get('https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20180914T205319Z.b0ffef87e97badd3.e78787ec8a392b9772f8b8f56933b1d86463d330&lang=' + selectedLang + '&text=' + searchText)
.then((response) => {
let translateInput = document.querySelector('#translation');
translateInput.value = response.data.text[0];
})
.catch((err) => {
console.log(err);
});
} else {
document.querySelector('#translation').value = '';
}