我的asp.net页面中有以下图片:
<asp:Image ID="imgExpCol" AlternateText="plus" ClientIDMode="Static" ImageUrl="~/theImages/subTaskPlus.png" runat="server" CssClass="imgExpCol" />我的JQuery中包含以下内容:
$(function () {
$("body").on('click', "#imgExpCol", function () {
alert("test");
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "../theImages/subTaskMinus.png");
$(this).attr("alt", "minus");
});
$("body").on('click', "#imgExpCol", function () {
alert("test2");
$(this).attr("src", "../theImages/subTaskPlus.png");
$(this).attr("alt", "plus");
$(this).closest("tr").next().remove();
});
});单击加号时,它会展开TR并显示减号。单击减号时,它会折叠TR并显示加号。
如果我使用的是当前的#imgExpCol,两个事件都会触发。我正在使用两个图像不同的ALT文本。如何使用ALT文本而不是ID?
发布于 2014-09-10 20:47:35
您可以在选择器中使用alt属性,因此您的JS将变为:
$(function () {
$("body").on('click', "#imgExpCol[alt=firstalttext]", function () {
alert("test");
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "../theImages/subTaskMinus.png");
$(this).attr("alt", "minus");
});
$("body").on('click', "#imgExpCol[alt=secondalttext]", function () {
alert("test2");
$(this).attr("src", "../theImages/subTaskPlus.png");
$(this).attr("alt", "plus");
$(this).closest("tr").next().remove();
});
});发布于 2014-09-10 20:49:46
使用单击处理程序并使用条件来了解alt。根据情况,做点什么。
$("body").on('click', "#imgExpCol", function () { //Is delegation really needed here?
//$("#imgExpCol").on('click', function () {
if($(this).attr('alt') === 'plus'){
alert("test");
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "../theImages/subTaskMinus.png");
$(this).attr("alt", "minus");
}else{
alert("test2");
$(this).attr("src", "../theImages/subTaskPlus.png");
$(this).attr("alt", "plus");
$(this).closest("tr").next().remove();
}
});性能提示:将$(this)缓存到变量中。它会阻止你创建x个jQuery对象。
发布于 2014-09-10 20:50:05
绑定两个事件并不好,例如使用类来确定元素的状态。
$(function () {
$("body").on("click", "#imgExpCol", function(){
var t = $(this);
// check if is expanded
if(t.hasClass("expanded"))
{
t.attr("src", "../theImages/subTaskPlus.png");
t.attr("alt", "plus");
t.closest("tr").next().remove();
t.removeClass("expanded");
}
else
{
t.closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
t.attr("src", "../theImages/subTaskMinus.png");
t.attr("alt", "minus");
t.addClass("expanded");
}
});
});https://stackoverflow.com/questions/25765765
复制相似问题