2016-11-27 91 views
0

我试图添加一个CSS类到li标签,该标签在执行jQuery ajax调用后附加到html。目标是当鼠标光标位于该元素上时向所添加的li元素添加左边框,并在鼠标离开li元素时移除边框。但是,代码不会执行,并且没有向li标签添加边框。向附加元素添加类

我的jQuery:

$(document).ready(function() { 
    $("#searchButton").on('click', function() { 
    var searchValue = $('.form-control').val(); 
    var urlVar = "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchValue + "&format=json&callback=?"; 
    $.ajax({ 
     type: "GET", 
     url: urlVar, 
     contentType: "json", 
     async: false, 
     dataType: "json", 
     success: function(searchData) { 
     $('#output').html(" "); 
     for (var i = 0; i < searchData[1].length; i++) { 
      $('#output').prepend(searchData[1][i] + '<li id="listItems"><a href=' + searchData[3][i] + '>' + searchData[2][i] + '</a></li>'); 
      $('#output a').attr('target', '_blank') 
     } 
     }, 
     error: function() { 
     alert("Something is off, man!!!") 
     } 
    }); 
    }); 
    $('#listItems').mouseenter(function() { 
    $(this).addClass('listFormat'); 
    }); 
    $('#listItems').mouseleave(function() { 
    $(this).removeClass('listFormat'); 
    }); 
}); 

我的CSS:

listFormat { 
border-left: 5px black solid; 
} 

只是真的不知道如何解决这个问题。

非常感谢。

+0

首先,为什么不在追加该项目时添加该类,并使用适当的css:'listFormat:hover'? – junkfoodjunkie

+0

你尝试添加只有CSS? – Dkouk

+0

#listItems li:first-child {border-left:1px solid red; } –

回答

0

快速回答很可能是为了监听动态添加的元素上的事件,您需要使用on方法。

$('#listItems').on('mouseenter', function() { 
    $(this).addClass('listFormat'); 
    }); 
    $('#listItems')on('mouseleave', function() { 
    $(this).removeClass('listFormat'); 
    }); 

而且虽然,因为@junkfoodjunkie说,你提议的技术是完全可行的,但有点过于复杂,因为已经有将应用样式有用的CSS标签时,在元素上移动鼠标。一个简单的例子见http://www.w3schools.com/cssref/sel_hover.asp

+0

好点。 CSS:hover解决方案更加优雅,易于实现。谢谢。 – Dovydas55