jQuery获取点击链接的ID [英] jQuery getting ID of clicked link
问题描述
我在jQuery中创建了一个模式框,用于显示一些嵌入代码。 我希望脚本采用点击链接的 id
,但似乎无法实现此功能。
I have a modal box in jQuery which I have created to display some embed code. I want the script to take the id
of the link that is clicked but I can't seem to get this working.
有人知道我该怎么做,或者为什么会发生这种情况?
Does anyone know how I can do that or why this may be happening?
我的jQuery代码是:
My jQuery code is:
function generateCode() {
var answerid = $('.openembed').attr('id');
if($('#embed input[name="comments"]:checked').length > 0 == true) {
var comments = "&comments=1";
} else {
var comments = "";
}
$("#embedcode").html('<code><iframe src="embed.php?answerid=' + answerid + comments + '" width="550" height="' + $('#embed input[name="size"]').val() + '" frameborder="0"></iframe></code>');
}
$(document).ready(function () {
$('.openembed').click(function () {
generateCode();
var answerid = $('.openembed').attr('id');
$('#box').show();
return false;
});
$('#embed').click(function (e) {
e.stopPropagation()
});
$(document).click(function () {
$('#box').hide()
});
});
我的加价是:
My mark-up is:
<a href="#" id="7830" class="openembed">Embed</a>
<a href="#" id="9999" class="openembed">Embed</a>
推荐答案
您的问题在这里:
$('.openembed')
返回一个匹配元素的数组。你应该只选择被点击的元素。
$('。openembed')
如果您将点击
事件分配给所有具有这个班。但另一方面,你无法知道点击的是什么。
returns an array of matched elements. Your should instead select only the clicked element.
$('.openembed')
works correctly if you assing a click
event to all elements that have this class. But on the other hand, you're unable do know which is clicked.
幸运的是,在处理函数主体中,单击可以调用 $ (this)
。
But fortunately in the body of handler function click you could call $(this)
.
$(this)
会返回当前(并点击元素)。
$(this)
will return the current (and clicked element).
// var answerid = $('.openembed').attr('id'); // Wrong
var answerid = $(this).attr('id'); // Correct
// Now you can call generateCode
generateCode(answerid);
另一个错误是 generateCode
函数的主体。在这里您应该传递选定元素的ID。这是正确的实现。
Another error is the body of generateCode
function. Here you should pass the id of selected element. This is the correct implementation.
function generateCode(answerid) {
if($('#embed input[name="comments"]:checked').length > 0 == true) {
var comments = "&comments=1";
} else {
var comments = "";
}
$("#embedcode").html('<iframe src="embed.php?answerid=' + answerid + comments + '" width="550" height="' + $('#embed input[name="size"]').val() + '"frameborder="0"></iframe>');
}
这里我已经用正确的行为实现了你的代码: http://jsfiddle.net/pSZZF/2/
Here I have implemented your code with the correct behavior: http://jsfiddle.net/pSZZF/2/
这篇关于jQuery获取点击链接的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!