简体   繁体   English

通过onclick方法将id传递给函数

[英]Passing id into function from onclick method

I know there are many of these types of questions already on here, but I can't find one that matches my specific case. 我知道这里已经有很多这类问题,但是我找不到与我的具体情况相符的问题。

I just want to pass an id variable into a function from an onclick event, but there's something not right about the way I've got is set up 我只是想将onclick事件中的id变量传递给函数,但是我的设置方式有些不对劲

The goal is to be able to remove the rows that have been added when the X is clicked 目的是能够删除单击X时添加的行

 $(document).ready(function () {
    $("#subjectlist")
        .change(function () {
            console.log("hit");
            $("select option:selected").each(function () {
                console.log($("select option:selected"));
                var id = 1;
                $('#overview').append("<tr id='id'><td>" +
                    $(this).text() + "</td><td id='id' 
onclick='removeItem(id)'>" + "X" + "</td></tr>");
                id = id + 1;                    
            });
        })
        .trigger("change");

    $(".btn1").click(function () {
        $("#subjectlist").toggle();
    });
});

function removeItem(id) {
    console.log(id.val);
    console.log(id);
    $('#overview').find('tr td').eq(id).remove();
}

If your goal is to remove the 'td' element that is clicked. 如果您的目标是删除单击的'td'元素。 Try this... 尝试这个...

$(document).ready(function () {
  var id = 1;
  $("#subjectlist")
      .change(function () {
          console.log("hit");
          $("select option:selected").each(function () {
              console.log($("select option:selected"));
              //var id = 1; moved this initialization up a scope level
              //on the line below I corrected the concatenation to have unique id's, and removed inline click event.
              $('#overview').append("<tr id='id'><td>" + $(this).text() + "</td><td id="+id+">" + "X" + "</td></tr>");
              id = id + 1;                    
          });
      })
      .trigger("change");

  $(".btn1").click(function () {
      $("#subjectlist").toggle();
  });
  // added click event to your dynamic element
  $("#overview").on('click','td', function() {
    $(this).parent().remove();
  });
});

/* removed
function removeItem(id) {
  console.log(id.val);
  console.log(id);
  $('#overview').find('tr td').eq(id).remove();
}*/

Try changing this 尝试改变这个

 $('#overview').append("<tr id='id'><td>" + $(this).text() + "</td><td id='id' onclick='removeItem(id)'>" + "X" + "</td></tr>");

To this... should be less confusing, regarding the quote-nesting... notice the use of backticks (`) on the outermost quote level. 为此,关于引号嵌套,应减少混乱。请注意在最外面的引号级别使用反引号(`)。 Also restyled it to make it easier to read, and match html syntax more visually. 还对其进行了重新样式设置,以使其更易于阅读,并且更直观地匹配html语法。

 $('#overview').append(
   `<tr id=x_id_`+id+`>` +
     `<td>` + 
       $(this).html() +
     `</td>` +
     `<td onclick="$('#x_id_` +
       id +
     `').remove()">` +
       `X` +
     `</td>` +
    `</tr>`
  );

You can ditch the removeItem function entirely. 您可以完全放弃removeItem函数。

Since I don't have the rest of your code, not totally sure about the change to the $().html vs $().text, but this should produce a clickable element that will remove the whole row with that id label, which is coded into the rows id and the onclick function. 由于我没有剩下的代码,因此无法完全确定$()。html与$()。text的更改,但这应该会产生一个clickable元素,该元素会删除带有该id标签的整行,它被编码到行ID和onclick函数中。

This will produce html like: 这将产生类似html的代码:

<tr id=x_ix_1><td>PREVIOUS STUFF HERE</td><td onclick='removeItem(`x_id_1`)'>X</td></tr>

Couple things: 几件事情:

First, keep in mind you can only have one element with a particular id at a time. 首先,请记住,一次只能有一个具有特定ID的元素。 Duplicates will cause errors (but you can remove an element with a particular id and make a new one with that same id, they just can't co-exist). 重复会导致错误(但是您可以删除具有特定ID的元素,然后使用相同ID制作一个新元素,但它们不能共存)。

If you don't want the row removed, but just the td, move the bit about the elements id from the tr to the td-- can't have same id on both. 如果您不希望删除行,而只是删除td,则将元素id的位从tr移到td上-两者不能有相同的id。

The quote-nesting was incorrect with the id variable, so was adding it as litteral text (just the string 'id', not the variable content)... id变量的引号嵌套错误,因此将其添加为乱码(只是字符串“ id”,而不是变量内容)...

And html id's need to start with a letter. html id必须以字母开头。 So I re-nested it so the id will parse as variable contents, and the html output will contain 'x_id_' prepended to the variable content... ie x_id_0 x_id_1 etc. 因此,我重新嵌套了该ID,以便将id解析为变量内容,并且html输出中将在变量内容之前包含“ x_id _” ...即x_id_0 x_id_1等。

Your appending string is incorrectly formatted. 您的附加字符串格式错误。

Drop the id attribute on the table column since your removeItem() function should be targeting the table row. 因为您的removeItem()函数应该以表行为目标,所以将id属性放在表列上。

You can use back ticks to generate template literals like so... 您可以使用反勾来生成模板文字,例如...

$('#overview').append(`<tr id="${id}">
  <td>${$(this).text()}</td>
  <td onclick="removeItem(${id});"> X </td>
</tr>`);

The jQuery.eq() function is an index based filter, not an selector filter. jQuery.eq()函数是基于索引的过滤器,而不是选择器过滤器。 You can then utilise the id selector... 然后,您可以使用ID选择器...

function removeItem (id) {
  $(`#${id}`).remove();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM