簡體   English   中英

使用javascript顯示和隱藏動態生成的ID

[英]Showing and hiding dynamically generated ID's with javascript

下面的代碼顯示和隱藏DIV的內容dynamically generated id's喜歡div_1, div_2div 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM