如何基于数据属性加载文件?
由于某种原因,$(这个)似乎不起作用。
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:30:17
代码中的this是窗口(全局对象)。我认为您的意思可能是让它引用具有data-*属性的元素。
您可能希望单独处理这些元素,所以最好的方法是找到它们并使用each循环它们,这将使您可以单独针对它们,并使用this调用您的回调,并引用每个元素:
$('.html[data-load-file][data-load-content]').each(function() {
var $this = $(this);
$this.load($this.attr("data-load-file") + ' ' + $this.attr("data-load-content"));
});或者:
$('.html[data-load-file][data-load-content]').each(function() {
$(this).load(this.getAttribute("data-load-file") + ' ' + this.getAttribute("data-load-content"));
});它查找类html的所有元素以及我们需要的两个data-*属性,分别遍历它们,并使用它们的属性调用load。
Live plunkr:http://plnkr.co/edit/lzHBYxVSETvHzTt6l2KR?p=preview
附带注意:我将上面的内容改为使用attr而不是data,因为没有任何迹象表明您正在使用data提供的特性。请记住,data是,而不是,是data-*属性的访问器。不止是这样。Details。
发布于 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
复制相似问题