展开和折叠按钮javascript

展开和折叠按钮javascript,javascript,html,Javascript,Html,我正在研究一个按钮的展开和折叠。我这里有两张图片,焦点应该放在元素上。如果单击一次,它应折叠,再次单击应展开。我尝试聚焦元素,但.focus()不起作用 HTML: <td aria-expanded="false" name="td_tohide2" id="td_tohide2" style="padding:0px;" class="sectiontd" nowrap="true" > <img role="button" aria-labelledby="hid

我正在研究一个按钮的展开和折叠。我这里有两张图片,焦点应该放在元素上。如果单击一次,它应
折叠
,再次单击应
展开
。我尝试聚焦元素,但
.focus()
不起作用

HTML

<td  aria-expanded="false" name="td_tohide2" id="td_tohide2" style="padding:0px;" class="sectiontd" nowrap="true" >
  <img  role="button" aria-labelledby="hide_show" id="generalinfo_caretup" src="images/arrow_up_ps_oc.png" onkeypress="sh_keypress('td_tohide2','td_toshow2','generaltable',event)" onclick="sh('td_tohide2','td_toshow2','generaltable')" tabindex="0" />
</td>

<td aria-expanded="true" aria-labelledby="hide_show_" name="td_toshow2" id="td_toshow2" style="padding:0px;display:none" class="sectiontd" nowrap="true">
  <img role="button" id="generalinfo_caretdown" src="images/arrow_down_ps_oc.png" onkeypress="sh_keypress('td_toshow2','td_tohide2','generaltable',event)" onclick="sh('td_toshow2','td_tohide2','generaltable')" tabindex="0" />
</td>

谁能告诉我如何聚焦元素。

什么是
sh
?您尚未提供具有该名称的函数。假设提供了该函数并遵循相同的模式,则需要确保将
b
的值传递到
setTimeout

当前
setTimeout
b
的值很可能未定义。这是因为默认情况下,
setTimeout
是在全局上下文中执行的。相反,您可以这样做:

function sh_keypress(a,b,c,event) {
    if(event.keyCode==13 || event.keyCode==32 || event.which==13 || event.which==32) {  
        if(document.getElementById(c).style.display === 'none') {
            document.getElementById(c).style.display = "";
        } else {
            document.getElementById(c).style.display = "none";
            document.getElementById(a).style.display="none"; //arrow images
            document.getElementById(b).style.display=""; //arrow images
            // Use a function below to provide the value of `b` from `sh_keypress` scope
            setTimeout(function(){document.getElementById(b).focus()},1000);
            event.stopImmediatePropagation();
        }
    }
}

你能分享一个更完整的代码示例吗?看起来你只分享了部分代码,我分享了html和js函数,你说焦点,焦点就像你一样。但不要为setTimeout提供字符串,而是提供一个真正的函数。将
“…”
转换为
函数(){…}
@anuu:请提供一个完整的示例。
sh
函数在您的代码中不存在,因此我无法确定问题发生在何处。我现在也将sh函数放入了。。你能检查一下吗焦点不起作用了
function sh_keypress(a,b,c,event) {
    if(event.keyCode==13 || event.keyCode==32 || event.which==13 || event.which==32) {  
        if(document.getElementById(c).style.display === 'none') {
            document.getElementById(c).style.display = "";
        } else {
            document.getElementById(c).style.display = "none";
            document.getElementById(a).style.display="none"; //arrow images
            document.getElementById(b).style.display=""; //arrow images
            // Use a function below to provide the value of `b` from `sh_keypress` scope
            setTimeout(function(){document.getElementById(b).focus()},1000);
            event.stopImmediatePropagation();
        }
    }
}