开发者

Need to create dynamic text for menus with Javascript

I need to assign dynamic text values to certain elements which can then be placed throughout a site I'm working on, as it will need to be localized later at some point.

I was hoping creating a list of them in JS like below-

document.getElementsById('title').innerHTML="Title1 Text";
document.getElementsById('title2').innerHTML="Title2 Text";

But of course 开发者_开发问答I want to have multiple copies of the title, title2 divs throughout, which won't work because of the getElementsById structure. Does anyone have any other suggestions or workarounds?


You can always use classes instead of ID's, something like

<p class="introText">Title1 Text</p>
<p class="closingText">Title2 Text</p>

And instead of affecting just one you could affect all of them and should you want to target just one, you can add an ID to that one.

<p class="introText" id="topIntro">Title1 Text</p>
<p class="closingText">Title2 Text</p>
<p class="introText">Title1 Text (again)</p>


You'll want to use classes instead of id. but JavaScript doesn't have a getElementsByClass() function by default so unless you want to use something like JQuery, you would have to define the function yourself.

document.getElementsByClass = function(class){
   var itemsfound = new Array;
   var elements = document.getElementsByTagName('*');
   for(var i=0;i<elements.length;i++){
      if(elements[i].className == class){
         itemsfound.push(elements[i]);
      }
   }
   return itemsfound;
}

this will return an array of elements with the specified class. then you can use the following code as needed.

document.getElementsByClass('class'); // gives an array of elements of given class
document.getElementsByClass('class')[0]; // selects first element in array with given class

but if you were to use JQuery, it's as simple as doing this:

$('.title').html("Title 1 Text");
$('.title2').html("Title 2 Text");

hope this helps in some way. cheers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜