我试图访问jquery选择器中的php变量,但它无法工作。这个php变量取自foreach php语句的视图页面。检查下面的代码。
HTML:
<?php foreach($items as $key => $value):?>
<div id="uploader<?php $value['id'] ?>">Upload</div>
<?php endforeach?>
上面的代码适用于concat字符串。
jQuery:
$(document).ready(function($) {
$("#uploader<?php echo $value['id'] ?>").uploadFile({
url:"YOUR_FILE_UPLOAD_URL",
fileName:"myfile"
});
});
现在我想将php变量连接到jquery元素选择器中,但上面的代码不起作用。在这里最好做什么?感谢
在不使用php的情况下尝试以下答案,选择id以上传程序开头的所有元素
$(document).ready(function($) {
$('div[id^="uploader"]').uploadFile({
url:"YOUR_FILE_UPLOAD_URL",
fileName:"myfile"
});
});
或者更安全地使用类
<?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"
});
});
您也可以使用~
来选择任何具有值作为上传程序的id。
$(document).ready(function($) {
$('div[id~="uploader"]').uploadFile({
url:"YOUR_FILE_UPLOAD_URL",
fileName:"myfile"
});
});
参考:
[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"