简体   繁体   English

Javascript更改背景颜色与功能和列表项的CSS

[英]Javascript change background color with function and css of a list item

i have a function with the following segment as seen below and what i want to do is to modify the background color of a list item when people click the edit button that is inside the list. 我有一个具有以下段的功能,如下所示,我想要做的是当人们单击列表中的编辑按钮时修改列表项的背景颜色。 Somehow i don't get is to work. 不知何故,我得到的是工作。 So the idea is to use the unique id for each list item of the group and use that one as an unique id in the second function, what am i doing wrong. 因此,我们的想法是为组中的每个列表项使用唯一ID,并在第二个函数中将其用作唯一ID,我做错了什么。

function datafromJSON(id_program) {
$.ajax({
    url: "/xxxxxx",
    type: "GET",
    success: function (data) {

        $.each(data, function (i, item) {

     var li = '<li id='ihaveaname ' + dataidfromdb + '" style =background-color:transparent;" > '
           + ' < a href = "" id = "clickonme" > < span class = "icon-edit" < /span></a > '
           + ' < /li>';

         $('#clickonme').click(function () {
           $('#ihaveaname' + dataidfromdb  + '').css("background-color", "red");
         });

      });
   });
}

in general it's not good idea to create click handler on each anchor, instead you can use bubbling of events to parent, and you should add to achor class .edit-parent for filtering of edit events... 一般来说,在每个锚上创建单击处理程序并不是一个好主意,而是可以使用事件冒泡到父级,并且应该添加到achor类.edit-parent以过滤编辑事件...

$('ul.parentofli').on('click', '.edit-parent', function(event) {
  $(event.target).closest('li').css('background-color', 'red');
});

Here is the answer i found, for the people that interest it. 以下是我发现的答案,对于那些感兴趣的人。 Since it is a list and the items get repeated the ID's get repeated as well and you're not allowed to use the same id twice. 由于它是一个列表并且项目重复,因此ID也会被重复,并且不允许两次使用相同的ID。 So by renaming the id to a unique name as well (in this case i added also the dataid to that one the function works perfect. Now i am able to use various css effects on the list elements or any other div therefor on the page. 因此,通过将id重命名为唯一名称(在这种情况下,我也将dataid添加到该名称,该功能完美。现在我可以在列表元素或页面上的任何其他div上使用各种css效果。

function datafromJSON(id_program) {
$.ajax({
url: "/xxxxxx",
type: "GET",
success: function (data) {

    $.each(data, function (i, item) {

 var li = '<li id='ihaveaname ' + dataidfromdb + '" style =background-color:transparent;" > '
       + ' < a href = "" id = "clickonme ' + dataidfromdb + '" > < span class = "icon-edit" < /span></a > '
       + ' < /li>';

     $('#clickonme' + dataidfromdb +').click(function () {
       $('#ihaveaname' + dataidfromdb  + '').css("background-color", "red");
     });

  });
 });
}

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

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