简体   繁体   中英

JavaScript / jQuery concatenating variables

To start with this. I have an associative array named $body (PHP).

Let's say I want to get the value of $body[1] or $body[2] , depending on the id of an element.

So here's my code.

$(document).ready(function() {
  $('.messages').on('click', function() {
    var id = $(this).attr('id');
    $('#generic-modal-title').html('Message Preview');
    $('#generic-modal-body').html('" . $body[-concatenate id here-] . "');
  });
})"

What I tried doing (doesn't work):

$('#generic-modal-body').html('" . $body["id"] . "');

Check this out i have tested this working fine as you required

<?php $body = array(0 => "content") ?>

<script>
$(document).ready(function() {
  var id  = 0;
  <?php echo "var body = " . json_encode($body) .";"; ?>
  $('#generic-modal-body').html(body[id]);
});

<div id="generic-modal-body"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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