【问题标题】:How to get the parent div id in javaScript?如何在 javaScript 中获取父 div id?
【发布时间】:2014-12-10 17:09:22
【问题描述】:

在每个 div 中选择 HTML“select”标签中的每个选项时,我想获取父 div id(div 类称为“col-sm-2”)。但它总是在“id”警报中仅提供最新添加产品的 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 检查我的答案。

标签: javascript php jquery html


【解决方案1】:

尝试使用each:

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

【讨论】:

    【解决方案2】:

    您使用closest() 获取直接容器 div 的 id 属性:

    $('select').on('change',function() {
       alert($(this).closest('div').prop('id'));
    });
    

    【讨论】:

      【解决方案3】:

      使用此代码

      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'));        
      };
      

      【讨论】:

        【解决方案4】:

        试试这个:

        Fiddle

        $('#formats_id').change(function(){
        
            alert($(this).parent().attr('id'));
        });
        

        【讨论】:

          【解决方案5】:

          首先我们将开始进行选择:

          $('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');

          两者都有效,但搜索深度不同:)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-01-27
            • 2022-11-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-03-31
            相关资源
            最近更新 更多