Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在父元素上迭代_Javascript_Jquery_Html_Css_Iteration - Fatal编程技术网

Javascript 在父元素上迭代

Javascript 在父元素上迭代,javascript,jquery,html,css,iteration,Javascript,Jquery,Html,Css,Iteration,我有一些类似以下的HTML(示例1): 我还有一些类似于以下内容的HTML(示例2): 我有一些jQuery代码如下: $(document).ready(function() { $('.surveyor_radio').parent().parent().append('<a class="reset-button">Reset</a>'); $('.reset-button').click(function () {

我有一些类似以下的HTML(示例1):


我还有一些类似于以下内容的HTML(示例2):


我有一些jQuery代码如下:

$(document).ready(function() {
  $('.surveyor_radio').parent().parent().append('<a class="reset-button">Reset</a>');

  $('.reset-button').click(function () {
      $('#'+$(this).data('question-id') + ' input[type="radio"]:checked').prop('checked', false).trigger('change');
  });

  $('fieldset').each(function () {
      var qid = $(this).attr('id');
      $('.reset-button', $(this)).attr('data-question-id', qid);
  });
});
$(文档).ready(函数(){
$('.surveyor_radio').parent().parent().append('Reset');
$('.reset按钮')。单击(函数(){
$('#'+$(this).data('question-id')+'input[type=“radio”]:checked').prop('checked',false.).trigger('change');
});
$('fieldset')。每个(函数(){
var qid=$(this.attr('id');
$('.reset button',$(this)).attr('data-question-id',qid);
});
});
jQuery代码有三个功能:

一个为单选问题添加重置按钮,另一个在单击重置按钮后取消选中这些问题,而第三个为重置按钮的
数据问题id
属性分配适当的id号

问题 示例2中的代码是正确的,
数据问题id
与其父项的id匹配,
字段集id

但是,字段集并不总是包含正确的
数据问题id
,如示例1所示,其中它是特定行的id

始终可以依赖的一个假设是,正确的id始终是重置按钮的父项

问题 如何适当地迭代每个重置按钮父项,获取其id,然后设置重置按钮的
数据问题id


我最好的尝试是类似于
$(“.reset button”).parent().each().attr(“id”)

迭代
.reset按钮
元素,并将每个
数据问题id
设置为家长id:

$(".reset-button").each(function() {
    $(this).data('question-id', $(this).parent().attr('id'));
});
请注意,在DOM检查器中查看数据属性时,这不会改变它,因为jQuery会在内部存储该属性,但会改变稍后使用
data()检索的值

你也可以这样做:

$(".reset-button").attr('data-question-id', function(i, val) {
    return this.parentNode.id || val;
});

我非常感谢你,在两分钟内你解决了我花了三个多小时的问题。它工作得很好,我基本上明白我做错了什么。再次感谢。
$(".reset-button").each(function() {
    $(this).data('question-id', $(this).parent().attr('id'));
});
$(".reset-button").attr('data-question-id', function(i, val) {
    return this.parentNode.id || val;
});
$(".reset-button").each(function() {
    var rid = $(this).parent().prop('id'); // get the parent ID
    $(this).data('question-id',rid); // set the data-question-id of the reset button 
});