views:

37

answers:

3
<table>
...
</table>

<script type="text/javascript">
$(selecctor).click(...)
</script>

The above is to be dynamic loaded by ajax.

What I want to do is restrict the selector so that it only affects the DOM within the table above it.I( can't assign an idto the table)

EDIT

To Gumbo's solution:

<div id="container">
</div>
<table>
..
</table>

I think for the above html,it will fail,because $('table:last') is not the newly loaded table,but the table after container

+1  A: 

You can pass a context element with the second parameter:

$("selector", $("table")).click(...)

Then the selector is evaluated based on that context.


Edit    Try table:last to select the last added node:

$("selector", $("table:last")).click(...)

This should work as only the nodes up to the SCRIPT element are already added to the DOM. But this does only work if you call $ directly and not via $.ready or $(document).ready.

Gumbo
`$("table")` is not enough to restrict the affecting range.
@user198729: Then how can you identify that particular table out of context?
Gumbo
I don't know.I guess some magical guys may know:)
To your edited answwer:the container is not necessarily located at the end of `body`.
@user198729: But you’re still referring to the nearest preceding table, right?
Gumbo
@Gumbo,I've updated my post as why it's wrong.
A: 

Add a class to the table.

<table class="myUniqueClass">...</table>

$(".myUniqueClass").click(...);
Andrew
The `table` may be loaded multiple times,each time populated with different data.
And... if you explain a little more about what you are doing you may get the help you need.
Andrew
It's the comment @pixeline.
if you are trying to reference some part of a dynamically loaded page using the jQuery.load method you can do something like$("#Container").load("myfile.php .myUniqueClass");
Andrew
I don't want to leave the listener-adding jobs to the **loading** page,but the **loaded** page instead
+1  A: 

You should show the whole html being loaded via ajax, as well as the html that will receive the loaded content.

But, say you are loading this table inside a div#mycontent and assuming there will only be one table:

$('#mycontent table:first').click();

Or better, assuming you should call your javascript in the ajax callback and separate the js and the html

$('#mycontent').load('file.php',function(data){
var selector = $('table',data).eq(0);
});
pixeline
This way will definately work.However,I want to make it possible that all I need to do is `$('container').load('file.php')`.The listeners are added in `file.php` itself.
well, i'm sorry to tell you this: there is no *reliable way* to do what you ask. Why do you keep such bad constraints (not separating the code and the behaviour, not giving an id or class to your table) ?Why use jquery if you don't use it the way it should be used?
pixeline