質問

I am reloading a div within my page to reflect variables which have been updated by the user. With my present method the variables are written into the page via a script tag that is imbedded in the body as follows:

JavaScript

cat = 1;

$("a#foo").click(function() {
    cat = cat + 1;
});

$("a#bar").click(function() {
    $('#bat').load('./index.html #bat > *');
});

HTML

<a href="#" id="foo">add another cat</a>

<a href="#" id="bar">update count</a>

<div id="bat">
    <script> document.write(cat); </script>
</div>

Any thoughts or suggestions are much appreciated. And here is a a jsfiddle for your tinkering convenience.

役に立ちましたか?

解決

Are you just reloading the page on clicking the link? I would say you do something like this instead of putting a script tag in your .

HTML

<span id="numberOfCats"></span>

Script

$("a#bar").click(function() {
    $('#numberOfCats').text(cat)
});

他のヒント

If you do not need to use your variable in the backend, i'd would be better to do that without ajax.

Just change $('#bat').load('./index.html #bat > *'); to $('#bat').text(cat);

You could also do the text() in a#foo click, so you don't have to update your counter manually.

Fiddle 1: http://jsfiddle.net/4eSEC/1/

Fiddle 2: http://jsfiddle.net/4eSEC/5/

If you want execute js code from script tags loaded througth Ajax with HTML -you neet to use $.globalEval

$("a#bar").click(function() {
    $('#bat').load('index.html #bat',function(newhtml){
        // execute included script tags - assumes inline for now
        $('script', newhtml).each(function() {
            $.globalEval($(this).text());
        });

    });
});

taken from: <script> not returned in AJAX

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top