[英]Showing and hiding dynamically generated ID's with javascript
下面的代码显示和隐藏DIV的内容dynamically generated id's
喜欢div_1, div_2
从div id
,一切似乎工作除了它需要像点击div_1应当公开的内容和点击div_2应隐藏时隐藏一个DIV内容精div_1。 请帮助我解决这个问题。
echo "<span class='bold'><a name='form_a_$group_seq' href='#div_$group_seq' id='form_a_$group_seq' value='1' " .
"onclick='return divclick(this,\"div_$group_seq\");'";
if ($display_style == 'block') echo "clicked";
echo "<b>" . xl_layout_label($group_name) . "</b></a></span>\n";
echo "<div id='div_$group_seq' class='section' style='display:$display_style;'>\n";
echo " <table border='0' cellpadding='0'>\n";
$display_style = 'none';
}
else if (strlen($last_group) == 0) {
echo " <table border='0' cellpadding='0'>\n";
}
下面是使代码可行的JavaScript。 但一次显示或隐藏所有div内容。
function divclick(a, divid) {
var divstyle = document.getElementById(divid).style;
if ( divstyle.display == 'none' ) {
divstyle.display = 'block';
} else {
divstyle.display = 'none';
}
return true;
}
这是浏览器正在渲染的一段更新的html代码。
<div class='container2'><ul class='taby'><li class='dropown'><a name='form_a_1' href='#div_1' id='form_a_1' value='1' onclick='return divclick(this,"div_1");'>Who</a></li></ul>
<div id='div_1' class='section'>
<table border='0' cellpadding='0'>
<div id='div_2' class='section'>
<table border='0' cellpadding='0'>
<div id='div_3' class='section'>
<table border='0' cellpadding='0'>
这实在太混乱了,无法使用和理解。 您应该考虑清理动态呈现html的方式,当您遇到此类问题时,这样的问题将更容易解决。 或一起阻止它们。
<span class='bold' style='background:#0DCAD1'>
<a name="<?php echo "form_a_$group_seq";?>" href="<?php echo "#div_$group_seq";?>" id="<?php echo "form_a_$group_seq";?>" value='1'>
等等....
如果以回显字符串形式呈现所有html,则以后将很难处理。 特别是在处理大量渲染的应用程序时。
如果您在页面中使用jQuery,则可以在代码中添加一行
function divclick(a, divid) {
var divstyle = document.getElementById(divid).style;
if ( divstyle.display == 'none' ) {
$(".section").css('display', 'none');
divstyle.display = 'block';
} else {
divstyle.display = 'none';
}
return true;
}
如果您不在页面上使用jquery,它会变得有些复杂,但只需添加几行即可完成。
function divclick(a, divid) {
var divstyle = document.getElementById(divid).style;
if ( divstyle.display == 'none' ) {
var sections = document.getElementsByClassName('section');
Array.prototype.forEach.call(sections, function(section){
section.style.display = 'none';
});
divstyle.display = 'block';
} else {
divstyle.display = 'none';
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.