dongye9182 2013-03-11 22:27
浏览 220

如何在Jquery中创建动态id选择器?

My php code goes something like this way-

for($i=1;$i<=$n;$i++)
{
$id='selectThisID-' . $i;
?>
<div id="<?php echo $id;?>">On Select this Div(say #selectThisID-3)<?php echo $field-n; ?></div>

<?php $id= 'paraID-' . $i;
<p id="<?php echo $id; ?>" style="display:none">Toggle this para(say #paraID-3) for selected ID only</p>
}

Now how can I handle this variable number of id's in my jQuery. As I know for single div statement it could be:

    <script>
        $(document).ready(function(){
            $("[id^=selectThisID-]").click(function(){
                $("[id^=paraID-]").toggle();
            });
        });
</script>

So on selecting element with id '#selectThisID-1', <p> will toggle. How can I use #selectThisID-2, #selectThisID-3....#selectThisID-n as jQuery selector. How can I get value of 'n' from php code to jQuery? Please help.

Thanks in advance.

Edit:

Suppose $n=5, so there are total 5 div elements. Now the problem is that when I select any of div(say #selectThisID-3) all <p> elements get toggled(i.e.

with #paraID-1, #paraID-2....#paraID-5 all toggled). However I need to toggle para-3 when div-3 selected, toggle para-4 when div-4 selected and so on. Please help.

  • 写回答

4条回答 默认 最新

  • douyouming9180 2013-03-11 22:29
    关注
    $("[id^=selectThisID-]").click(function(){
        $("#paraID-"+this.id.split('-')[1]).toggle();
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题