Пример:
Установить атрибут id для всех элементов div, основанном на их позиции на странице.
"jQuery"
$("div").attr("id", function (arr) { return "div-id" + arr; }) .each(function () { $("span", this).html("(ID = '" + this.id + "')"); });
"HTML"
<div>Zero-th <span></span></div> <div>First <span></span></div> <div>Second <span></span></div>
"CSS"
div { color:blue; }
span { color:red; }
b { font-weight:bolder; }
"Живой пример jQuery"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link href="http://slyweb.ru/css/jqueryiframe.css"
rel="stylesheet" type="text/css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div").attr("id", function (arr) {
return "div-id" + arr;
})
.each(function () {
$("span", this).html("(ID = '" + this.id + "')");
});
});
</script>
</head>
<body class="iframe">
<div>Zero-th <span></span></div>
<div>First <span></span></div>
<div>Second <span></span></div>
</body>
</html>
<style>
div { color:blue; }
span { color:red; }
b { font-weight:bolder; }
</style>
Пример:
Установить src атрибут из title атрибута для всех элементов img. Изображения находятся в images/.
"jQuery"
$("img").attr("src", function() {
return "images/" + this.title;
});
"HTML"
<img title="ptica1.gif"/> <img title="ptica2.gif"/> <img title="ptica3.gif"/>
"CSS"
div { color:blue; }
span { color:red; }
b { font-weight:bolder; }
"Живой пример jQuery"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link href="http://slyweb.ru/css/jqueryiframe.css"
rel="stylesheet" type="text/css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("img").attr("src", function() {
return "images/" + this.title;
});
});
</script>
</head>
<body class="iframe">
<img title="ptica1.gif"/>
<img title="ptica2.gif"/>
<img title="ptica3.gif"/>
</body>
</html>
<style>
div { color:blue; }
span { color:red; }
b { font-weight:bolder; }
</style>