如何在JavaScript中获取父级div的ID?

3
我希望在每个div的HTML“select”标签中选择每个选项时,能够获取父div id(div类名为“col-sm-2”)。但是它总是只给出最新添加的产品的div id。例如,如果我最后添加的产品的id是“7”,那么它总是作为警报给出“7”。
以下是用于获取产品id的PHP代码。
$jsql_ae7 = mysql_query("select request_list.product_id from request_list where request_list.product_id='{$jrowa2['id']}' and request_list.email='$visit_email'") or die(mysql_error());
$jfeta7 = mysql_fetch_assoc($jsql_ae7);

这是我的HTML代码。

<div class="col-sm-2" id="<?php echo $jfeta7['product_id']; ?>">
    <select id="formats_id" name="aformats" onchange="showFormat(this);">
        <option value="<?php echo $jrowa2['formats']; ?>"><?php echo $jrowa2['formats']; ?></option>
            <?php foreach($formats3 as $v3){  ?>
                <?php if($v3 !== $jrowa2['formats']) { ?>
                    <option value="<?php echo $v3; ?>"><?php echo $v3; ?></option>
                <?php } ?>          
            <?php } ?>

    </select>
</div>

这是我的 JavaScript 代码。

var showFormat = function(dd) {
    var format_value = dd.options[dd.selectedIndex].value;
    var scriptTags = document.getElementsByTagName('select');
    var id = scriptTags[scriptTags.length - 1].parentNode.id;
    alert(id);        
};

使用 JavaScript 检查我的答案。 - Nishit Maheta
5个回答

9

尝试使用each函数:

$('select').each(function() {
   alert($(this).parent().attr('id'));
});   

1
您可以使用closest()方法获取最近的容器div元素的id属性:
$('select').on('change',function() {
   alert($(this).closest('div').prop('id'));
});

1
使用这段代码。
var showFormat = function(dd) {
     var format_value = dd.options[dd.selectedIndex].value;
    var scriptTags = document.getElementsByTagName('select');
    var parent = scriptTags[scriptTags.length - 1].parentNode;
    alert(parent.getAttribute('id'));        
};

1
尝试这个:

Fiddle

$('#formats_id').change(function(){

    alert($(this).parent().attr('id'));
});

1
首先,我们将开始进行选择:
$('select').each(function() {
   var selectField = $(this); // this will point to select element
});

有两种方法:
  1. 这将直接选择select的父元素

    selectField.parent().attr('id');

  2. 这将选择第一个祖先元素,它是具有“my-class”类的div:

    selectField.closest('div.my-class').attr('id');

两种方法都可以使用,但搜索深度不同 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接