Javascript:根据 nput type= 的值更改 data-target= "#" "text"



>场景:如果用户插入 1 并单击搜索,则数据目标应该是 nophase,如果是 2,那么它应该是 withphase。 我

正在尝试在javascript上弄清楚,有人可以帮我一把吗?

网页代码:

<label for="inputPRNO" class="sr-only">PRNO</label>
<input id="act1" type="text" class="form-control" placeholder="PRNO">
<button class="btn btn-primary mb-2" type="button" data-toggle="collapse" data-target="#nophase" aria-expanded="false" aria-controls="collapseExample"> Search </button>
<div class="collapse" id="nophase">
<div class="card card-body">
No phase.
</div>
</div>
<div class="collapse" id="withphase">
<div class="card card-body">
With phase.
</div>
</div>

好吧,它不会出现,因为上面的代码中有任何文本字段,但我想你打算包含它,所以假设你有<input type="text" id="inserter">,只需添加一个事件侦听器到提交按钮,检查输入的值,并相应地更改数据属性

ok.addEventListener("click", e=> {
if(inserter.value.toString() == "1") {
ok.setAttribute("data-target", "#nophase");
} else if(inserter.value.toString() == "2") {
ok.setAttribute("data-target", "#withphase");
}
console.log(ok.getAttribute("data-target"));
});
<input type="text" id="inserter">
<button id="ok" data-target="#nowith">Submit</button>

假设我们有这些HTML代码:

function setSource(){
let inputValue=document.getElementById('inputText');
let btn=document.getElementById('btn1');

btn.setAttribute('data-target','#nophase');
if(inputValue.value==2){
btn.setAttribute('data-target','#phase');
}

let phasex=btn.getAttribute('data-target');

console.log(phasex);
}
<div>
<label>Input text</label><input id="inputText" />
<button id="btn1" class="btn btn-primary mb-2" type="button" data-toggle="collapse" data-target="#nophase" aria-expanded="false" aria-controls="collapseExample" onClick="setSource()"> Search</button>
</div>
<div class="collapse" id="nophase">
<div class="card card-body">
No phase.
</div>
</div>
<div class="collapse" id="withphase">
<div class="card card-body">
With phase.
</div>
</div>

最新更新