Javascript 函数在单击时触发
如何触发此功能:Javascript 函数在单击时触发,javascript,html,Javascript,Html,如何触发此功能: <script> function change(x) { var target = document.getElementById("target"); if (y == "imgA") {target.className = "cast1";} else if (y == "imgB") {target.className = "cast2";} else if (y == "imgC") {targe
<script>
function change(x) {
var target = document.getElementById("target");
if (y == "imgA") {target.className = "cast1";}
else if (y == "imgB") {target.className = "cast2";}
else if (y == "imgC") {target.className = "cast3";}
else if (y == "imgD") {target.className = "cast4";}
else {target.className = "chart";}
}
function changeReset() {
var target = document.getElementById("target");
target.className = "chart";
}
</script>
功能改变(x){
var target=document.getElementById(“目标”);
如果(y==“imgA”){target.className=“cast1”}
如果(y==“imgB”){target.className=“cast2”}
如果(y==“imgC”){target.className=“cast3”}
如果(y==“imgD”){target.className=“cast4”}
else{target.className=“chart”;}
}
函数changeReset(){
var target=document.getElementById(“目标”);
target.className=“图表”;
}
仅在按下此按钮时发生
<div class='nfooter' style="position:float;"><a id="c_question" href="#"><img src="../name_footer/_name.png" /></a></div>
向元素添加onclick=“change()”
编辑:
或者,如果您的意思是只允许函数在被特定元素调用时执行,则可以检查该元素。此
引用将引用拥有该功能的元素
function change(x) {
if(this.id == "target")
var target = document.getElementById("target");
if (y == "imgA") {target.className = "cast1";}
else if (y == "imgB") {target.className = "cast2";}
else if (y == "imgC") {target.className = "cast3";}
else if (y == "imgD") {target.className = "cast4";}
else {target.className = "chart";}
}
}
编辑2:
通常您会使用元素进行绑定。onclick
但是,当使用内联声明时,此
引用引用引用窗口
这里的细节
在不过度修改代码的情况下,您可以按照下面的建议稍微修改函数
function change(element,x) {
if(element.id=="target"){
var target = document.getElementById("target");
if (y == "imgA") {target.className = "cast1";}
else if (y == "imgB") {target.className = "cast2";}
else if (y == "imgC") {target.className = "cast3";}
else if (y == "imgD") {target.className = "cast4";}
else {target.className = "chart";}
}
}
然后更改内联onclick以传递对元素的引用onclick=“更改(此为“目标”)”
通常认为使用内联onclick声明是不好的做法。因此,考虑在脚本中执行单击绑定。在函数定义中添加另一个参数对象,在函数调用中使用“这个”。
然后通过id在函数定义中检查object.id是你想要的。希望你得到了逻辑。你可以使用
document.getElementById(“c_-question”)
和addEventListener
或者你可以将onclick
属性添加到a
链接中。前者是更可取的方法。什么按钮?我看到一个div、一个锚点和一个映像。您希望附加这两个函数中的哪一个?另外,change
的参数应该是什么?'need2nobasis'.replace('is','ics')
I onclick=change('target')是否可以这样,如果代码中的任何地方有另一个函数,那么如果没有id target的特定引用,它将不会触发?这是什么意思?如果你的意思是你可以检查一个特定的目标,你可以在你的功能。如果您指的是另一个具有不同参数的change函数,那么这是javascript中无法实现的。这叫做函数重载,不受支持。不确定“签入函数”是什么意思。哦,是的,我注意到了。谢谢你所做的一切。非常感谢。我还添加了returnfalse,我再次更新了代码,并添加了一个有用的链接。
function change(element,x) {
if(element.id=="target"){
var target = document.getElementById("target");
if (y == "imgA") {target.className = "cast1";}
else if (y == "imgB") {target.className = "cast2";}
else if (y == "imgC") {target.className = "cast3";}
else if (y == "imgD") {target.className = "cast4";}
else {target.className = "chart";}
}
}