How to get value to array in javascript
$array = array("1" => "box of chocolates", "2" => "mylar ball开发者_StackOverflow中文版oons", "3" => "stuffed animals");
<?php
$productWithItem = $array;
foreach ($productWithItem as $pwi) {
?>
<a href="#" id="product_name"><?php echo $pwi->name ?></div></a>
<?php
}
?>
<script type="text/javascript">
jQuery(function(){
var value_array = ?;
});
</script>
I Want get array value from id="product_name", but I don't know get value from on this javascript, you can help me, thank you
If you are intending to keep your <script>
in your html code, build your array in php and use echo
:
<script type="text/javascript">
jQuery(function(){
var value_array = <?php echo $yourarray ?>;
});
</script>
That's not an elegant solution, though.
Make product_name as id into class . now $('.product_name') this will be automatically array of objects
example markup
<a href="#" class="product_name">aaa</div></a>
<a href="#" class="product_name">bb</div></a>
<a href="#" class="product_name">cc</div></a>
using each you can extract array
$('.product_name').each(function(){
alert($(this).text());
});
Put your array string in the name
attribute of the <a>
.
Then you can use jQuery to get it back:
jQuery(function(){
var ele= [YOUR ELEMENT]
var value_array = $.parseJSON($(ele).attr("name"));
});
精彩评论