最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add class to li with specific ID - Stack Overflow

programmeradmin0浏览0评论

I want to add a class to a li with specific Id. I tried this:

function updateIndex(indexValue){
    $('li[id=' + indexValue + ']').addClass("selectedQuestion")

}

I am not able to access indexValue variable in the li selector.

I want to add a class to a li with specific Id. I tried this:

function updateIndex(indexValue){
    $('li[id=' + indexValue + ']').addClass("selectedQuestion")

}

I am not able to access indexValue variable in the li selector.

Share Improve this question edited Jun 23, 2015 at 12:16 Vivek Sadh asked Jun 23, 2015 at 12:10 Vivek SadhVivek Sadh 4,2683 gold badges35 silver badges54 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

You need to do a string concatenation to use the value of the indexValue parameter:

$('li[id=' + indexValue + ']').addClass("selectedQuestion")

Or, given the attribute you are selecting by is an id:

$('li#' + indexValue).addClass("selectedQuestion");

Or, given that id is supposed to be unique you shouldn't need the 'li' part (unless your meaning is to select that element only if it has that id and is an li element):

$('#' + indexValue).addClass("selectedQuestion");
function updateIndex(index){
   $('li[id=' + index +']').addClass("selectedQuestion")

}

Use this code instead of yours. You have to concatinate the indexValue variable

function updateIndex(indexValue){
  $('li[id=' + indexValue + ']').addClass("selectedQuestion")

}
发布评论

评论列表(0)

  1. 暂无评论