开发者

adding links with javascript

I have h1 tag, which id called "step1". I would like to add link for that with Javascript. So i trying to code with javascript as follow:

    div = document.getElementById('step1');
 newlink = document.createElement('a');
  newlink.setAttribute('class', 'heading');
 newlink.setAttribute('href', 'javascript:showStep(2);');
 div.appendChild(newlink);

But it r开发者_如何学运维ender only this way. <h2 id="step1">Step<a href="javascript:showStep(1);" class="heading"> in HTML.

Actually I want following result as :

    <h2 id="step1"><a href="javascript:showStep(2);" 
class="heading">Choose Desired Services</a></h2>

So please help me to create this.


If you're just adding an element to trigger some JavaScript behavior, there's absolutely no need for it to be an <a> tag. Just make a <span> and set its "onclick" attribute to the function you want to call:

var div = document.getElementById('step1');
var newlink = document.createElement('span');
newlink.onclick = function() { showStep(2); };
newlink.innerHTML = "Choose Desired Services";
div.appendChild(newlink);

You can also give it a class name etc. so that it can be styled appropriately (pointer cursor, whatever).

Also, don't forget var!!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜