使用jQuery将动态内容预处理为多个元素
Prepend dynamic content to multiple elements with jQuery
当然这很容易,但由于不知道要搜索的确切单词,很难搜索到答案:/
如果有更好的方法,请告诉我;)
基本上,我正在生成一些具有各种内容和标题的div框
所以在我的html页面中,我有:
<div class="itdSec" data-title="What is This">
This is a magical div box with some stuff in it
</div>
在我的js文件中,我有
$(".itdSec").prepend("<div class='itdSecTit'>" + this.data("title") + "</div>");
目的是在div的顶部添加一个div,其中包含数据标题arribute 的内容
"这个"导致了错误,因为这仍然是主页面。并且使用CCD_ 1代替它每次返回第一个。
这是有效的:
$(function(){
$(".itdSec").prepend(function() {
return "<div class='itdSecTit'>" + $(this).data("title") + "</div>";
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="itdSec" data-title="What is This">
This is a magical div box with some stuff in it
</div>
或者你可以这样做:
$(function(){
$(".itdSec").each(function() {
$(this).prepend("<div class='itdSecTit'>" + $(this).data("title") + "</div>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="itdSec" data-title="What is This">
This is a magical div box with some stuff in it
</div>
使用$('.itdSec')
可以选择类别为.itdSec
的所有元素,但是prepend
只适用于一个元素。
您需要做的是使用jQuery的.ech()对所有选定的元素进行迭代,并为每个元素预先设置标题。
$('.itdSec').each(function(i) {
// 'i' is the index (0,1,2,3...) - not needed here
// 'this' is now every element in turn
var title = $(this).data('title');
$(this).prepend('<div class="itdSecTit">' + $(this).data("title") + '</div>');
});
(JSFiddle)
在.each()循环中,您可以使用this
作为当前正在迭代的元素。
相关文章:
- Javascript 二进制搜索/插入预处理
- 如何在元素中处理鼠标事件,但不能在其子元素上处理
- 节点.js未捕获的异常类型错误:无法设置未定义的预处理 ''
- 克隆内容,附加和预处理
- 元素事件处理程序到EXT.js面板中
- 上传到FTP之前预处理文件
- 2秒后删除新的jQuery预处理节点
- 对象是't可在同一html画布元素上处理和创建fabric画布后选择
- 预处理Emulator for JavaScript(定时/调试示例)
- 脚本预处理的基础知识
- 如何引用引导类型预处理的数据
- 使用 CSV 文件预处理高图表数据
- 在调用窗口模糊(浏览器失去焦点)时避免元素模糊处理程序
- 使用HTML5 / javascript更正音频音量输出分贝,关闭预处理
- Ruby on Rails 路由前缀,而不是在 .erb.js 文件中进行预处理
- 如何在咖啡脚本中预处理或包含咖啡脚本
- 在将每个 HTML 元素附加到 AngularJS 中的 DOM 之前对其进行预处理
- 使用jQuery将动态内容预处理为多个元素
- jQuery对元素进行追加、包装、预处理
- 如何从html onClick事件中将html预处理到页面上的元素中