dougang1967 2018-02-26 23:11
浏览 55
已采纳

使用来自多维PHP数组的特定键作为Javascript变量Jquery onClick [关闭]

I have a multi-dimensional PHP array where the key for each inner array is an ID of button I will be clicking and instantiating a jQuery function.

I basically want to dynamically create a javascript VAR array from that PHP array based on the Id that is clicked. Here is the array:

$ContentGroupIds = array(
    43 => array( 511, 531, 567 ),
    54 => array( 483, 499, 509 )
);

So you can see I have ContentGroupId's: 43 and 54 which each point to an array of ContentId's.

When I click on the button for ContentGroupId = 43, I need to dynamically set the jquery var to look like this:

var contentids = ['511','531','567'];

Then I can use that var in the rest of my jquery function.

  • 写回答

2条回答 默认 最新

  • dqpfl2508589 2018-02-26 23:51
    关注

    Set the ContentGroupID's as an attribute on your buttons (having your HTML output would help), and grab that attribute with jQuery.

    PHP/HTML:

    <?php
        $ContentGroupIds = array(
            43 => array( 511, 531, 567 ),
            54 => array( 483, 499, 509 )
        );
    
        foreach( $ContentGroupIds as $item => $ids ){
            // Convert ID Array to string
            $attr = implode( ',', $ids );
    
            // Output: <a href="#" class="btn" attr-ids="511,531,567">Button #43</a>
            echo '<a href="#" class="btn" attr-ids="'. $attr .'">Button #'. $item .'</a>';
        }
    ?>
    

    jQuery:

    $('body').on('click', '.btn', function(){
        var str = $(this).attr('attr-ids'),  // str = "511,531,567"
            arr = str.split(',');     // arr = ['511','531','567']
    
        console.log(arr); // (3) [0:"511", 1:"531", 2:"567"]
    });
    

    Functional Snippet:

    $('body').on('click', '.btn', function(){
        var str = $(this).attr('attr-ids'),
            arr = str.split(',');
    
        alert(arr);
    });
    /*CSS only to make the links more buttony*/a{display:inline-block;background:#0095ff;padding: 6px 18px;color:#fff;text-decoration:none;border:1px solid #07c;box-shadow:inset 0 1px 0 #66bfff;font-family:sans-serif;font-size:14px border-radius:3px;}a:hover{background: #0085ee;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href="#" class="btn" attr-ids="511,531,569">Button #43</a>
    <a href="#" class="btn" attr-ids="483,499,509">Button #54</a>

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型