简体   繁体   English

如何更改javascript for循环条件? 新手问题

[英]How to change javascript for loop criteria? Newbie question

Javascript newbie here, just trying to tweak this bit of code. 这里的Javascript新手,只是尝试调整这段代码。 It checks for all HTML elements with a title attribute and adds the class 'tooltipParent'. 它检查所有具有title属性的HTML元素,并添加类'tooltipParent'。

I'd like it to only add the class to elements with a title attribute AND the class 'tooltip'. 我希望只将类添加到具有title属性和类'tooltip'的元素中。 I think I need to add something to the for loop to check for this extra class? 我想我需要在for循环中添加一些内容来检查这个额外的类?

// loop through all objects with a title attribute
var titles=$('[title]');

// use an efficient for loop as there may be a lot to cycle through
for(var i=titles.length-1;i>-1;i--){

   // titled object must be position:relative
   $(titles[i]).addClass('tooltipParent');

}

Thanks! 谢谢!

You can put the class requirement into your original selector: 您可以将类要求放入原始选择器中:

$('*.tooltip[title]').addClass('tooltipParent');

This means 这意味着

  • select all elements ( * ) 选择所有元素( *
  • with the class "tooltip" ( .tooltip ) 使用“工具提示”类( .tooltip
  • and a title attribute set ( [title] ) 和标题属性集( [title]
  • and add the class tooltipParent 并添加类tooltipParent

You can extend your jQuery selector on the first line to select the proper elements. 您可以在第一行扩展jQuery选择器以选择适当的元素。 Look at the jQuery documentation for help. 查看jQuery文档以获取帮助。 It's probably something like var titles = $('.tooltip[title]') . 它可能类似于var titles = $('.tooltip[title]')

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

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