Javascript,CSS - Modal id while循环唯一id

时间:2016-09-27 09:01:28

标签: javascript php jquery css

嘿所有我有以下代码,它完美但我也希望在每个循环中使用相同的概念。这不起作用,因为没有唯一标识符。我怎么解决这个问题?下面是我的代码(每个循环都有)

.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 250px; /* Location of the box */
    left: 680;
    top: 0;
    width: 35%; /* Full width */
}

.modal-content {
    background-color: #fefefe;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
    min-height: 250;
}

.close {
    color: #aaaaaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}
.close :hover,
.close :focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}

然后我有一些PHP代码

    foreach ($myarray as $my_array) {

                       Select table etc


echo " <div class='col-sm-4 hides'> <button style='background-color: Transparent; border: none; padding: 0px 0px;' color='white' onclick=\"selected_comp('" . $received1['id'] . "','" . $comp_row['id'] . "','" . $comp_row['functions'] . "','" . preg_replace("/\r|\n/", "", $comp_row['comments']) . "')\"> <b>" . $comp_row['functions'] . "</b><br>";



echo "</button>";
if (strlen($comp_row['comments']) > 100){
echo "  
<a href='javascript:void(0);' id='showall3'>Volledige beschrijving. </a>
    <div id='myModal3' class='modal'>
    <div class='modal-content'>
        <span id='close3' class='close'>×</span>
        <p>
        <b> " . $comp_row['functions'] . " </b><br>
         " . nl2br($comp_row['comments']). "
        </p>
      </div>
    </div>
    ";      
}

我得到了一些javascript代码来显示模态(和隐藏)

var modal3 = document.getElementById('myModal3') ;
$('#close3').click(function(){
  modal3.style.display = 'none';
});
$('#showall3').click(function(){
  modal3.style.display = 'block';
});

1 个答案:

答案 0 :(得分:1)

将id更改为类,使用closest()&amp;获取模态主体选择相对于单击元素的元素。 next(),使用show / hide切换显示属性

echo "  
<a href='javascript:void(0);' class='showAll'>Volledige beschrijving. </a>
    <div  class='modal myModal'>
    <div class='modal-content'>
        <span class='close'>×</span>
        <p>
        <b> " . $comp_row['functions'] . " </b><br>
         " . nl2br($comp_row['comments']). "
        </p>
      </div>
    </div>
    "; 

$('.close').click(function(){
  $(this).closest('.myModal').hide();
});
$('.showAll').click(function(){
  $(this).next().show();
});