美好的一天,
我正在尝试找到一种使用链接替换标签值的方法,类似于选择标签-因此它在按下链接后会替换值。我在下面看到了此文件,它不能按预期工作:
function My1() {
let lblA = document.getElementById('My1lbl');
let lblB = document.getElementById('My1t1');
let lblC = document.getElementById('My1t2');
let replaceName = document.getElementById('replaceMy1').value;
let replaceTitle = document.getElementById('replaceMy1').title;
lblA.innerText = replaceName;
lblB.innerText = replaceTitle;
lblC.innerText = replaceTitle;
}
function My2() {
let lblA = document.getElementById('My2lbl');
let lblB = document.getElementById('My2t1');
let lblC = document.getElementById('My2t2');
let replaceName = document.getElementById('replaceMy2').value;
let replaceTitle = document.getElementById('replaceMy2').title;
lblA.innerText = replaceName;
lblB.innerText = replaceTitle;
lblC.innerText = replaceTitle;
}
<a href="javascript:My1()">Title 1<input id="replaceMy1" title="Title 1" value="1st Value" style="display: none"></a>
<a href="javascript:My2()">Title 2<input id="replaceMy2" title="Title 2" value="2nd Value" style="display: none"></a>
<span id="My1t1"><span id="My2t1">yet not replaced Title A</span></span>
<span id="My1t2"><span id="My2t2">yet not replaced Title B</span></span>
<label id="My1lbl"><label id="My2lbl">yet not replaced Value</label></label>
该代码段在这里不起作用,因此这里是CodePen上相同的代码(有效)。
如果您只有一个这样的函数,那就太好了,但是,如果您有两个或多个函数,那么它会干扰您的JS文件,而主要的缺点是,只有在第一次单击后才能起作用-如果您想返回一个值替换之前,链接不起作用。
基本上,我想实现此处的功能,但仅使用链接而不是选择/选项标签:https://codepen.io/anon/pen/NBbmqX。
任何想法如何克服这一挑战?
答案 0 :(得分:0)
您只需要1个函数,该函数将为被单击的元素输入an identifier
,并检索与之对应的数据并进行相应填充。另外,分别删除span
和label
中不必要的span
和label
。
尝试关注
function My(id) {
// Get the elements that needs to be updated
let lblA = document.getElementById('My1lbl');
let lblB = document.getElementById('My1t1');
let lblC = document.getElementById('My1t2');
// Get the corresponding values
let replaceName = document.getElementById('replaceMy' + id).value;
let replaceTitle = document.getElementById('replaceMy' + id).title;
// Update the element text
lblA.innerText = replaceName;
lblB.innerText = replaceTitle;
lblC.innerText = replaceTitle;
}
<a href="javascript:My(1)">Title 1<input id="replaceMy1" title="Title 1" value="1st Value" style="display: none"></a>
<a href="javascript:My(2)">Title 2<input id="replaceMy2" title="Title 2" value="2nd Value" style="display: none"></a>
<span id="My1t1">yet not replaced Title A</span>
<span id="My1t2">yet not replaced Title B</span>
<label id="My1lbl">yet not replaced Value</label>