简体   繁体   English

jquery在父div中选择类

[英]jquery select class inside parent div

I'm trying to change the alt of the image, I'm clicking by selecting the image's class ( add_answer ) 我正在尝试更改图像的alt,我点击选择图像的类( add_answer

Note: .add_answer shows up multiple times inside different containing div 's 注意: .add_answer 在不同的包含div显示多次

jQuery(function(){   // Add Answer

    jQuery(".add_answer").click(function(){
        var count = $(this).attr("alt");
        count++;
        $('.a_type_'+count+'').show();
        $(this).parents("div:first").$('.add_answer').attr("alt", count);
    }); 

});

This line doesn't seem to be working, how do I select this add_answer class by way of it's parent div 这行似乎不起作用,如何通过它的父div选择这个add_answer

$(this).parents("div:first").$('.add_answer').attr("alt", count);

Anyone else have an idea? 其他人有想法吗?

I'm trying having trouble decreasing the alt value on the .add_answer image when .destroy_answer is clicked 单击.add_answer时,我在尝试降低.add_answer图像上的alt值时.destroy_answer

jQuery(function(){   // Hide Answer

    jQuery(".destroy_answer").click(function(){
        $(this).parents("div:first").hide();
        var count = $('.add_answer').attr("alt");
        count--;
        $('.add_answer',$(this).parent('div:first')).attr('alt',count);


    }); 

});

Problem line: 问题线:

$('.add_answer',$(this).parent('div:first')).attr('alt',count);

您可以使用父div作为范围:

 $('.add_answer',$(this).parent('div:first')).attr('alt',count);

这应该工作:

$(this).parent("div").find(".add_answer").attr("alt", count);

You code is almost correct. 你的代码几乎是正确的。 Required change is to use .find instead of .$ after .parents method. 所需的更改是使用.find而不是。$ after .parents方法。 Use of .parent instead of .parents should be avoided, this way your code will be more unobtrusive (precisely - this way img can be non-direct child of the div). 应该避免使用.parent而不是.parents,这样你的代码就会更加不引人注目(正是这种方式,img可能是div的非直接子代)。

$(this).parents('div:eq(0)').find('.add_answer')

You can manipulate :eq(0) to select eg third parent div using :eq(2). 您可以使用以下方法操作:eq(0)以选择例如第三个父div:eq(2)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM