开发者

adding a mouseover to a link through javascript

Simple quick question....

I have the following link html:

<a href="http://www.site.com/" onmouseover="" />

I have a javascript function which I want to enter some开发者_如何学JAVA onmouseover information into that link dynamically. So, lets say it then becomes this for example if this javascript function is called:

<a href="http://www.site.com/" onmouseover="alert('howdy')" />

any ideas how to do this?


Add name attribute to and assign onmouseover

<a href="http://www.site.com/" onmouseover="" name="xxx"/> 
document.getelementsbyname('xxx').onmouseover = function() { alert('howdy') } 


Answer was, using setAttribute() javascript.


I think you want to say: dynamically change your href attribute information then you can do it by jquery

//Write code for prompt box and get value (when mouse-over)
$("a[href='http://www.google.com/']").attr('href', 'YOUR_GET_VALUE')


If you can use jquery, see: http://api.jquery.com/hover/

This is better than changing the attribute directly. Your javascript function can dynamically bind/unbind the mouse hover event and execute your alert call.

Otherwise your javascript function will need to dynamically change the attribute but you'll need to work around browser differences to locate the correct element then locate and modify the onmouseover attribute.


two options:

if it's something small:

<a href="http://www.site.com/" onmouseover="this.href = 'http://stackoverflow.com'" />

if you have something more to do:

<script type="text/javascript">
    function doSomething(elem) {
        elem.href = 'http://stackoverflow.com';
    }
</script>
<a href="http://www.site.com/" onmouseover="doSomething(this)">test</a>

Or as stated before: use jQuery or any other framework to make your life a lot easier


The following works for jQuery every time

first the javascript:

  $(document).on('mouseenter','.hovLink', function (e) {
       e.preventDefault();
       e.stopPropagation();
       alert('entering ' + e.target.id);
  }).on('mouseleave','.hovLink', function (e) {
       alert('exiting ' + e.target.id);
  });

and here is the HTML

<a href="/link" class="hovLink" id="link1">Link</a>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜