jquery.attr()を使用してDiv IDを取得します
質問
.eachおよび.attr関数を使用して、Div IDを取得したいと思います。私はそれをする方法を知っていますが、私がやりたいのは、特定のクラスで各Div IDをDOMから取得することです(「編集」クラスとしましょう)。
私が問題を抱えていることは次のとおりです。その特定のdivのIDを.eachループに.append内に入れたいです。たとえば、.appendの内部にリンクを入れたい場合は、リンクを http://www.website.com/index.php?id=1&div=div-id
どんなアイデアでも、私は初心者ですので、コードの例を提供できます。私はattrを理解しています。
解決
このページにそれを保持するために:
HTML:
<div id="1" class="edit">A</div>
<div id="2" class="edit">B</div>
<div id="3">C</div>
JS:
// Anonymous loop, in case you copy and paste this script, the vars won't get confused
(function() {
// Loop for each .edit
$('.edit').each(function() {
// Update the text inside
$(this).html('http://www.website.com/id='+$(this).attr('id'));
});
})();
他のヒント
これは、それが機能するはずのように見えるテストされていないソリューションです。に割り当てられた複数のクラスがある場合、それは機能しないかもしれません div
要素。
$(function() {
$('div').each(function() {
var _t = $(this);
var id = _t.attr("id");
if(_t.attr("class") == "someClass") {
_t.append("<a href = 'http://www.website.com/index.php?id=1&div="+id+"'>Hello World!</a>");
}
});
});
推測します。あなたはこれを求めている?
$( '.edit' ).append( function () {
return '<a href="http://www.website.com/index.php?id=1&div=' +
this.id + '">link</a>';
});
私 考える 私はあなたの条件を正しく解釈しています:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
</head>
<body>
<div id="a" class="edit">A</div>
<div id="b" class="edit">B</div>
<div id="c">C</div>
<div id="d" class="save">D</div>
<div id="e" class="edit">E</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
(function ($) {
$("div.edit").each(function (i) {
var $div = $(this);
$div.append('<a href="http://www.website.com/index.php?id=1&div=' + $div.attr("id") + '">Link</a>');
});
})(jQuery);
</script>
</body>
</html>
アップデート: @johnhartsockは正しいです。ここではそれぞれの方法は必要ありません。次のようにコードを調整します。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
</head>
<body>
<div id="a" class="edit">A</div>
<div id="b" class="edit">B</div>
<div id="c">C</div>
<div id="d" class="save">D</div>
<div id="e" class="edit">E</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
(function ($) {
$("div.edit").append(function () {
var $div = $(this);
$div.append('<a href="http://www.website.com/index.php?id=1&div=' + $div.attr("id") + '">Link</a>');
});
})(jQuery);
</script>
</body>
</html>
各()へのjQueryの呼び出しが必要だとは思わない。と append() これがセレクターの現在の反復を表す関数を渡すことができます。
$('div.mydivclass').append(function () {
return '<a href="http://www.website.com/index.php?id=1&div='+ this.id + '">My Div link</a>';
});
これがフィドルです http://jsfiddle.net/wfd7k/
所属していません StackOverflow