最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript onclick even on a div not working - Stack Overflow

programmeradmin3浏览0评论

I have a div and when a user clicks on it using the onclick event, i'm calling a function:

   function test(a)
    {   

     alert(a);
   }

<div onclick="javascript:test('zaswde');">sdfasdasdadasdasds</div>​

Update

    <ul>
      <li> 
           <div>
       <div onclick="javascript:alert('v'); "></div>

           </div>
            <div ></div>
      </li>
    </ul>

Can't i use onclick on the div element? ​

I have a div and when a user clicks on it using the onclick event, i'm calling a function:

   function test(a)
    {   

     alert(a);
   }

<div onclick="javascript:test('zaswde');">sdfasdasdadasdasds</div>​

Update

    <ul>
      <li> 
           <div>
       <div onclick="javascript:alert('v'); "></div>

           </div>
            <div ></div>
      </li>
    </ul>

Can't i use onclick on the div element? ​

Share Improve this question edited Aug 6, 2012 at 5:49 asked Aug 6, 2012 at 5:42 user1415759user1415759 6
  • How are you attaching the onclick? – loganfsmyth Commented Aug 6, 2012 at 5:43
  • 1 How about you show us the whole code? Specifically the div with its onclick code. Is this function above or below that in the HTML? What errors does the console give? – sachleen Commented Aug 6, 2012 at 5:43
  • Your code is fine. You have some error somewhere else – zerkms Commented Aug 6, 2012 at 5:49
  • @Jalpesh Patel:update my html. – user1415759 Commented Aug 6, 2012 at 5:49
  • In its simplest form, the code works. DEMO. You'll have to provide more info/code. – sachleen Commented Aug 6, 2012 at 5:52
 |  Show 1 more ment

3 Answers 3

Reset to default 2

Onclick will call the function, you don't need the javascript:

<div onclick="test('zaswde');">sdfasdasdadasdasds</div>​

Your code is working fine.

Moreover You may use click events on any element including <div>

<div onclick="test('This is a <div> tag');">Click on this &lt;div&gt; element</div>

<span onclick="test('This is a <span> tag');">Click on this &lt;span&gt;</span>

<p onclick="test('This is a <p> tag');">Click on this &lt;p&gt;</p>

<a href="#" onclick="test('This is an <a> tag');">Click on this &lt;a&gt;</a>

See An Example Fiddle

Technically, your code will work. But most would argue that it is not the best way to write it.

I guess the reason why it is not working is because you already have a JavaScript error in your HTML page. Check the error console in your browser and see if there are any JavaScript error on it. If yes, then fix that and then this should work.

Edit:

I also see from your example that you don't have anything inside the div. So how are you sure that you are clicking inside the div. See if you can add a senstence or two inside the div, so that you get enough space to click inside the div.

发布评论

评论列表(0)

  1. 暂无评论