如何基于数据属性加载文件?
由于某种原因,$(这个)似乎不起作用。
if ($('.html').data('load-file')) {
$(this).load($(this).data("load-file") + ' ' + $(this).data("load-content"));
}body {
margin: 0;
padding: 0;
}
.html {
width: calc(100% - 10px);
height: 80px;
margin: 10px;
background: #f6f6f6;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div
class="html"
data-load-file="../index.html"
data-load-content=".icon_environment"></div>
<div class="html"></div>
发布于 2017-07-22 13:32:24
您的jQuery(这个)不是指您的div.html,而是指整个文档。
您需要将jQuery(this)替换为jQuery('.html'),或者获取每个div.html并制作一个附件以确保jQuery(这个)引用您的div.html。
还可以添加一个文档,以确保在没有div的情况下,在页面加载之前不会执行它。
jQuery(document).ready(function(){
jQuery('.html[data-load-file]').each(function(){
var loadFile = jQuery(this).data('load-file') ;
console.log(loadFile) ;
var loadContent = jQuery(this).data('load-content') ;
console.log(loadContent) ;
var load_url = loadFile + ' ' + loadContent ;
console.log(load_url) ;
jQuery(this).load(load_url);
}) ;
}) ;body {
margin: 0;
padding: 0;
}
.html {
width: calc(100% - 10px);
height: 80px;
margin: 10px;
background: #f6f6f6;}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div
class="html"
data-load-file="../index.html"
data-load-content=".icon_environment"></div>
<div class="html"></div>
https://stackoverflow.com/questions/45255083
复制相似问题