我想在HTML&#34中选择每个选项时获取父div id(div类被称为" col-sm-2");选择"每个div中的标记。但它总是只给出最新添加的产品的div id" 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);
};
答案 0 :(得分:8)
尝试使用each:
$('select').each(function() {
alert($(this).parent().attr('id'));
});
答案 1 :(得分:1)
您可以使用closest()
获取直接容器div的id属性:
$('select').on('change',function() {
alert($(this).closest('div').prop('id'));
});
答案 2 :(得分: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'));
};
答案 3 :(得分:1)
答案 4 :(得分:1)
首先,我们将从选择开始:
$('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');
两者都有效,但搜索深度不同:)