You have just make some control and Javascript in your webpart which looks similar as below:
Control
<div id=”btnX”></div>
Javascript
$('#btnX').click(function () {
$('#myTargetControl')...
..
});
Then you deployed it to your environment and place the webpart in a page. After adding the first webpart, you find that your script works as it intended. You might have some requirements to place the same webpart more than once in the same page. You proceed to add the same part a few more times in the same page.
When you tested it, you realised that the same script actually triggered multiple times (perhaps 5 times if you got 5 same webparts in a page)
How to solve it to make sure only the correct control is selected when you try trigger the script from a certain webpart or in this case the button that is in the same webpart as the targetted control?
Here’s the tricks for both control and javascript
Control – add the runat tag
<div id=”btnX” runat=”server”></div>
Javascript
– instead of calling the button ID directly, use ClientID as it will be unique for every webpart
– as long as the control and button are within same webpart and div, they will have same prefix which added with their own id. This case btnX and myTargetControl.
– the alert is put for testing purpose.
$('#<%=btnX.ClientID%>').click(function () {
var _thisX = $(this);
var _thisMyControl = _thisX.attr('id').replace('btnX', 'myTargetControl')
//alert(_thisX.attr('id') + "~~~" + _thisMyControl);
$('#'+_thisMyControl)...
..
});