質問

I'm importing an external php file into a different php file.

External file:

function featured($featured) {
echo '<button id="switch">CLICK ME!</button>';
echo '<object type="application/x-shockwave-flash" height="427" width="700" id="live_embed_player_flash" data="http://www.twitch.tv/widgets/live_embed_player.swf?channel=blahblah" bgcolor="#000000"><param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><param name="allowNetworking" value="all" /><param name="movie" value="http://www.twitch.tv/widgets/live_embed_player.swf" /><param name="flashvars" value="hostname=www.twitch.tv&channel=blahblah&auto_play=true&start_volume=25" /></object>';
}

Main file:

<div id="div">
</div>

<script>
    var xmlhttp;

    function loadXMLDoc(url, varString, cfunc){
        if (window.XMLHttpRequest)
            xmlhttp=new XMLHttpRequest();
        else
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        xmlhttp.onreadystatechange=cfunc;
        xmlhttp.open("POST", url, false);
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                    var channel = window.location.search;
                    if(channel.length>0)
                            varString = channel.substring(1);
        xmlhttp.send(varString);
    }   
    loadXMLDoc("external.php", "channel=", function(){ 
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
            document.getElementById("div").innerHTML=xmlhttp.responseText;
    });
</script>

The loadXMLDoc function works perfectly fine, I can see the elements and interact with the button and play the video in the object tag. However when I apply the following code to either the external file or the main file I get no interaction whatsoever.

<script>
$(document).ready(function(){
$( "#switch" ).click(function() {
  $( "object" ).attr("data", myNewURL);
});
});
</script>
役に立ちましたか?

解決

Try to use on():

$(document).ready(function(){
    $('body').on('click', "#switch", function() {
        $( "object" ).attr("data", myNewURL);
    });
});

Your #switch element was added after the .click() method, so it didn't have the event attached to it. In this case, event delegation will helps you to attach the click event to this newly added #switch element.

他のヒント

use on()

on() Attach an event handler function for one or more events to the selected elements.

<script>
$(document).ready(function(){
 $('body').on('click', "#switch", function() {
        $( "object" ).attr("data", myNewURL);
    });
});
</script>

you should use delegate for that

$(document).on("click","#switch",function(){
   //some operation
});

It helps you to attach handlers for the external loaded elements

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