Dynamically adding script / jquery function block

Edition:

Just wondering if it's possible to add a block (or a static script) or a variable to the html body.

Something like that,

$('body').add(function(){/../}) 

or

$('body').append('<script></script>')

or

$('body').fn.myFunc = function(){}

Is using .extend correct?

One example: if I use ExternalInterface, my callbacks should be statically defined in body / html / js, but not in the $ () function. ready if I don't have var globally defined and refer to it in the $ () function. ready.

I missed this requirement and I wanted to add dynamic callback functions.

+3
source share
4 answers
  • To create a script tag in your markup

    $('<script/>', {
        type:    'text/javascript',
        src:     'http://...'
    }).appendTo(document.body);
    
  • To expand jQuery, use

    $.fn.yourmethodname = function(){
    });
    
+4
source

$.getScript(), .

:

<script>$.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function(){
  $("#go").click(function(){
    $(".block").animate( { backgroundColor: 'pink' }, 1000)
      .animate( { backgroundColor: 'blue' }, 1000);
  });
});</script>
+2

Javascript, .

fn DOM , .

- :

$(function() {
    $('body')[0].fn = function() {};
    $('body')[0].fn.myFunc = function() { alert('Yay function'); };
});

, , body:

$('body')[0].myFunc = function() { alert('Yay function'); };

, [0] $('body'), JQuery, DOM . , , , $('body'), JQuery.

0

. script, .

, , .

, , , php , , , . , . , . php , .

  <script type="text/javascript"  >
  $(document).ready(function(){
  $("button").click( function() {
         $.get( "/menu_to_body_respond.php", {
        pageId: $thisPageId
        subSecID: $thisSubID
        }, function( resp ) {
            $("#left_body").html(resp);
            });
  });
 });
</script>

, , php- menu_to_body_respond.php

<?php
$pageIDVal = $_GET[ 'thisPageId'];
$subIDVal =  $_GET[ 'thisSubId'];

// code to decide what to do with this button press
// switch statements do a good job, if your 
// application has a lot of items you might want to respond to
//just put the most used items at the beginning of the switch.

//tmp code to give you a response
$outStr = $pageIDVal . " Left Body B2";
echo($outStr);
?>

You can cause it to mix, there are buttons that respond locally, such as general opening / failure of the general menu and work with basic clients. Just first enter the identifiers with names, and if one of them can answer, they will stop $ ('button'), launched simply with the if-else statement.

0
source

Source: https://habr.com/ru/post/1757097/


All Articles