简体   繁体   中英

Calling a php object inside jquery selector

I am trying to access php variable inside jquery selector but it can't get to work. This php variable is taken from the views page from a foreach php statement. Check the code below.

HTML:

<?php foreach($items as $key => $value):?>
 <div id="uploader<?php $value['id'] ?>">Upload</div>
<?php endforeach?>

The above code works concat string.

jQuery:

$(document).ready(function($) {
  $("#uploader<?php echo $value['id'] ?>").uploadFile({
  url:"YOUR_FILE_UPLOAD_URL",
  fileName:"myfile"
  });
});

Now I wanted to concat the php variable inside the jquery element selector but code above won't work. What would be the best thing to do here? Thanks

You can also use ~ for selecting any id have the value as uploader.

$(document).ready(function($) {

    $('div[id~="uploader"]').uploadFile({
        url:"YOUR_FILE_UPLOAD_URL",
        fileName:"myfile"
    });
});

Ref:

[attribute^=value]  $("[title^='Tom']") All elements with a title attribute value starting with "Tom"
[attribute~=value]   $("[title~='hello']")  All elements with a title attribute value containing the specific word "hello"
[attribute*=value]  $("[title*='hello']")   All elements with a title attribute value containing the word "hello"

Try the following answer without php, select all the elements that have a id that starts with uploader

$(document).ready(function($) {
  $('div[id^="uploader"]').uploadFile({
  url:"YOUR_FILE_UPLOAD_URL",
  fileName:"myfile"
  });
});

or safer use a class

<?php foreach($items as $key => $value):?>
 <div class="toupload" id="uploader<?php $value['id'] ?>">Upload</div>
<?php endforeach?>

js:

$(document).ready(function($) {
      $('.toupload').uploadFile({
      url:"YOUR_FILE_UPLOAD_URL",
      fileName:"myfile"
      });
    });

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