[英]How to get the parent div id in javaScript?
我想在每個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);
};
嘗試使用每個 :
$('select').each(function() {
alert($(this).parent().attr('id'));
});
您coild獲得使用即時div容器的id屬性closest()
$('select').on('change',function() {
alert($(this).closest('div').prop('id'));
});
使用此代碼
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'));
};
首先,我們將從選擇開始:
$('select').each(function() {
var selectField = $(this); // this will point to select element
});
有兩種方法:
這將直接選擇父母
selectField.parent()ATTR( 'ID')。
這將選擇第一個祖先,它是一個帶有'my-class'類的div:
selectField.closest( 'div.my級')ATTR( 'ID')。
兩者都有效,但搜索深度不同:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.