简体   繁体   English

将数组值从html传递到javascript

[英]Passing array value from html to javascript

Note: using the Laravel framework but the concept shouldn't be too different. 注意:使用Laravel框架,但是概念应该没有太大不同。

How would I go about passing my $data['method'] and $data['id] to javascript? 如何将$data['method']$data['id]传递给javascript?

<div id="player" data-method="{{ $data['method'] }}" data-id="{{ $data['id'] }}"></div>

Data method and Data id are passed through a controller. 数据方法和数据ID通过控制器传递。

In javascript I've currently got 在javascript中,我目前有

var method = "<?php echo $data-id[]>";
var id = "<?php echo $data-method[]>";

Which obviously don't work 哪个显然不起作用

To get the method: 获取方法:

var method = document.getElementById("player").getAttribute("data-method");

And to get the id: 并获取ID:

var id = document.getElementById("player").getAttribute("data-id");

In addition to @chris97ong answer, if you use jQuery, then you can use such constructions: 除了@ chris97ong答案,如果您使用jQuery,则可以使用以下构造:

var method = $('#player').data('method');
var id = $('#player').data('id');

But if you want to paste id and method values directly to javascript, then use: 但是,如果要将ID和方法值直接粘贴到javascript中,请使用:

var method = "<?php echo $data['id']>";
var id = "<?php echo $data['method']>";

Exactly like in your own way. 完全像您自己的方式。

Jeffrey Way提供了一个不错的插件,可将变量传递给控制器​​中的JavaScript: https//github.com/laracasts/PHP-Vars-To-Js-Transformer

You can pass array as 您可以将数组传递为

<?php
    $array = array("a","b","c","d");
    $json_str = json_encode($array);
?>
<a str='<?php echo $json_str; ?>' class="array_pass">Pass Value</a>

<script>
$(document).ready(function(e) {
    $(".array_pass").click(function() {
        var str = $(this).attr("str");
        var array = jQuery.parseJSON(str);
        alert(array[0]);
    });
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM