原型选择帮助

时间:2009-10-18 00:33:49

标签: javascript prototypejs css-selectors

嘿伙计们,我正在努力为我使用的网络应用添加一小部分内容。现在我正在尝试检查页面上具有类.checkBox的所有复选框(如果需要区分/选择)。复选框是类.someClass的div的后代,只是有许多具有该类的div。我想检查哪些是div的后代,其类只有 .someClass

换句话说:

<!-- Check this box -->
<div class="someClass"> [...] <input type="checkbox" class="checkBox" /></div>

<!-- But not this one -->
<div class="someClass otherClasses lolWut"> [...] <input type="checkbox" class="checkBox" /></div>

请记住,复选框不是直接子项,而是后代。

谢谢,我将不胜感激任何帮助:)

1 个答案:

答案 0 :(得分:3)

你走了:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <title>Check the boxes</title>
    <script src="prototype.js" type="text/javascript"></script>

    <script type="text/javascript">
    function checkThem() {
      // get all the .someClass divs
      $$(".someClass").each(function(item) {
        // filter out the ones that have additional classes 
        if(item.className == 'someClass') {
          // get the .checkBox descendants
          item.select('.checkBox').each(function(checkbox) {
            // check them
            checkbox.checked = true;
          });
        }
      });   
    }
    </script>

</head>

<body>

  <!-- Check this box -->
  <div class="someClass">Check: <input type="checkbox" class="checkBox" /><input type="checkbox" class="checkBox" /></div>

  <!-- But not this one -->
  <div class="someClass otherClasses lolWut">Don't check: <input type="checkbox" class="checkBox" /></div>

  <!-- Check this box -->
  <div class="someClass">Check: <input type="checkbox" class="checkBox" /><input type="checkbox" class="checkBox" /></div>

  <br /><br />

  <a href="#" onclick="checkThem(); return false;">Check them.</a>

</body>
</html>