通过Javascript(KeywordScript)设置ID

时间:2012-12-07 23:26:59

标签: javascript html search keyword

我正在为学校做这项任务,但我找不到某个逻辑。我几乎100%确定它是setElemId()函数,它应该设置并返回元素id,但它不会一直返回,当我为快速链接设置href时,它只是设置{ {1}}而不是#

HTML

ID

的Javascript

<body>
   <div id="page">
      <div id="logo"><img src="hlogo.jpg" alt="Historic Documents" /></div>
      <div id="logosub">Department of History<br />Midwest University</div>

      <div id="doc">
         <h1 id="doctitle">The Federalist Papers <br />No. 10</h1>
         <p id="docsubtitle">The Union as a Safeguard Against 
            Domestic Faction and Insurrection<br />From the New York Packet. Friday, 
            November 23, 1787.</p>

         <p id="intro">To the people of the state of New York:</p>

         <p id="firstp">Among the numerous advantages promised by a well-constructed 
            Union, none deserves to be more accurately developed than its 
            tendency to break and control the violence of faction. The friend of 
            distresses under which we labor have been erroneously charged on the 
         </p>

         <p>By a <dfn id="firstkey">faction</dfn>, I understand a number of 
            citizens, whether amounting to a majority or a minority of the whole, 
            interest, adversed to the rights of other citizens, or to the permanent 
            and aggregate interests of the community.</p>

         <p>The other point of difference is, the greater number of citizens and 
            extent of territory which may be brought within the compass of 
            the former than in the latter. The smaller the society, the fewer 
         </p>

      </div>
   </div>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

您似乎在搜索关键字的完全匹配。由于您的所有元素都不包含您正在寻找的关键字(而是包含文本),因此没有匹配项。

相反,请尝试if( elemTextArr[i].indexOf(elemText) > -1)

请注意,您似乎没有将搜索字词转换为小写字母,因此如果我输入大写字母,我将无法获得任何匹配。

答案 1 :(得分:0)

  

“它会点击if语句,但它会a)始终为false(就像它已经设置了ID)”

尝试更改:

if(elemList[i].id = null)

为:

if(!elemList[i].id)

您将id分配给null而不是将其与null进行比较(当您指的是===时,您使用了=== ),然后if会将其评估为null(falsy),并且每次都会进入else个案例。

此外,我认为您不想与null进行比较,因为未设置的id将不会null(当我尝试将其设置为未设置时{ {1}}是一个空字符串,id)。更容易使用""运算符来测试!是否为“falsy”。