我想在按下html按钮后将字符串值返回给p标签。我不确定如何编写/格式化和执行它。当myFunction返回true和/或false para innerHTML =''时,将在<p>
标记中打印出一个字符串。
const para = document.getElementById('para');
const palin = document.getElementById('palin');
const sub = document.getElementById('sub');
sub.addEventListener('click', function myFunction(str) {
let re = /[^A-Za-z0-9]/g;
str = str.toLowerCase().replace(re, '');
let len = str.length;
for (let i = 0; i < len/2; i++) {
if (str[i] !== str[len - 1 - i]) {
return true;
}
}
};
<form >
<input id = 'palin' type = 'text'></input>
<button id ='sub'>Submit</button>
<p id = 'para'></p>
</form>
答案 0 :(得分:0)
你为什么不试试这个
function abc(){
var a = document.getElementById('palin').value;
if(a!=''||a!=undefined){
document.getElementById('para').innerHTML=a;
}
}
<input id = 'palin' type = 'text'></input>
<button id ='sub' onclick="abc()">Submit</button>
<p id = 'para'></p>
答案 1 :(得分:0)
或检查此。由于默认情况下表单是提交的,因此请尝试删除表单标签并在eventListener中尝试一次,并且传递的参数将作为事件而不是字符串进行反应。
var para = document.getElementById('para');
var sub = document.getElementById('sub');
sub.addEventListener('click', function() {
var str = document.getElementById('palin').value;
let re = /[^A-Za-z0-9]/g;
str = str.toLowerCase().replace(re, '');
let len = str.length;
for (let i = 0; i < len; i++) {
if (str[i] !== str[len - 1 - i]) {
para.innerHTML=str;
return true;
}else{
para.innerHTML="Hello user";
}
}
});
<input id = 'palin' type = 'text'></input>
<button id ='sub'>Submit</button>
<p id='para'></p>