ak-SE ak-SE - 3 years ago 118
PHP Question

How to assign dynamic element id in jQuery when onMouseOver in a href tag?

I have 3 hyperlinks and DIV randomly generated by PHP script with dynamic ids. For example,

<a href="http://www.example.com/find.php?id=xy1" id="xy1" onMouseover="analyze('final', 'xy1')">xy1</a>
<a href="http://www.example.com/find.php?id=ay2" id="ay2" onMouseover="analyze('final', 'ay2')">ay2</a>
<a href="http://www.example.com/find.php?id=am3" id="am3" onMouseover="analyze('final', 'am3')">am3</a>

<div id="xy1"></div>
<div id="ay2"></div>
<div id="am3"></div>

I want to display some text based on the
event through a function
in jQuery. For example,

function analyze(db, target) {
type: "GET",
url: "toThumb.php",
data: 'db=' + db + '&id=' + target,
success: function(output){ $("#"+target).html(output); }

Here, the element id
must be automatically assigned based on
event. Like xy1 as a value of a variable name. Maybe on the next
event it will be ay2 or am3.

I tried to set with
It failed... If I test individually with
It works fine.

Does my way of coding is wrong? Or, Can I use
instead of passing parameters?

Answer Source

First of all id should be unique in DOM. And in place of it you can use class as below.

Please check below working demo.

function analyze(ele){
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://www.example.com/find.php?id=xy1" id="xy1" onMouseover="analyze(this)">xy1</a>
<a href="http://www.example.com/find.php?id=ay2" id="ay2" onMouseover="analyze(this)">ay2</a>
<a href="http://www.example.com/find.php?id=am3" id="am3" onMouseover="analyze(this)">am3</a>

<div class="xy1"></div>
<div class="ay2"></div>
<div class="am3"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download