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条)

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口