<a href="javascript:document.getElementById(&#39;morecontent1&#39;).style.display=&#39;block&#39;;"> not working

时间:2016-03-15 17:30:14

标签: javascript href

I tried this code to achieve a read more effect:

    <a href="javascript:document.getElementById('morecontent1').style.display='block';">Read more</a>
    <div class="morecontent" id="morecontent1">Additional content 1</div>

but unfortunately it is not working: The complete content disappears and only the text "block" is displayed. Why? The same code in onclick is working fine.

3 个答案:

答案 0 :(得分:1)

试试这个

   <script>
        function show(){
        javascript:document.getElementById('morecontent1').style.display='block';
        }
      </script>
      <body>
        <a type="button" onClick="show()">Read more</a>
        <div class="morecontent" id="morecontent1" style="display: none">Additional content 1</div>
      </body>

答案 1 :(得分:0)

您不应该使用内联JavaScript或内联事件处理程序,因为它们会创建难以调试的意大利面条代码(如您所见)和(事件处理程序)创建在事件处理函数中绑定<% if signed_in %>的全局函数包装器this而不是DOM元素。

window属性实际上不是触发JavaScript的地方,在大多数情况下,链接的点击事件是正确的位置。

此代码有效,但是DIV已经是块级元素,因此点击链接实际上什么都不做,所以我在这个例子中添加了一个额外的样式。

&#13;
&#13;
href
&#13;
window.addEventListener("DOMContentLoaded", function(){
   var theDiv = document.getElementById("morecontent1");
   var theLink = document.getElementById("link");
   
   theLink.addEventListener("click", function(){
      theDiv.style.display = "block";
      theDiv.style.border = "1px solid red";  // Just for fun!
   });

});
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

不行。用于单击事件以触发功能并重定向/触发书签/更改内容