osenel osenel - 1 month ago 7
HTML Question

Determining which element referred current html

I have a HTML page with two buttons. Both of these buttons referring same page, say Test2. While working on Test2(creating new elements etc..) I need to know which button was clicked. Here is an example code:

HTML1:


<head>
<title>Test 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>

<div class="Main" id="Main">
<div id="Div1">
<button id="Btn1" onclick="window.location.href='Test2.html';"> this is Button 1 </button>
</div>
<div id="Div2">
<button id="Btn2" onclick="window.location.href='Test2.html';"> this is Button 2 </button>
</div>
</div>

</body>
</html>


HTML2:


<head>
<title>Test 2</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<script type='text/javascript'>
if (1==1) { //if something happened
var aaa=window.document.referrer.source;
alert(aaa)}
</script>
</body>
</html>


This code results with "undefined" alert message. How could I get id of button or div that referred to Test2.html?

Answer

Given the use of onclick to just set the new location I would add a query parameter to each URL:

<button … onclick=onclick="window.location.href='Test2.html?btn=1';" … >#

And then parse the query string in the code in Test2.html.