From 1109132f09d75da9a28b649c7677bb6ce07c40c0 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:45 -0500 Subject: initial commit --- files/he/_redirects.txt | 50 + files/he/_wikihistory.json | 1136 ++++++++++++++++++++ files/he/archive/b2g_os/index.html | 75 ++ files/he/archive/index.html | 20 + files/he/dom/index.html | 13 + files/he/gecko_dom_reference/index.html | 10 + files/he/gecko_dom_reference/preface/index.html | 31 + files/he/glossary/css/index.html | 50 + files/he/glossary/html/index.html | 46 + files/he/glossary/index.html | 48 + .../\327\236\327\242\327\250\327\232/index.html" | 42 + files/he/he/index.html | 14 + files/he/hebrew_localization/index.html | 7 + files/he/learn/css/index.html | 64 ++ .../learn/getting_started_with_the_web/index.html | 61 ++ files/he/learn/html/index.html | 58 + .../index.html" | 34 + .../index.html" | 72 ++ .../index.html" | 55 + .../index.html" | 141 +++ files/he/learn/index.html | 98 ++ .../javascript/asynchronous/concepts/index.html | 203 ++++ files/he/learn/javascript/asynchronous/index.html | 43 + .../javascript/asynchronous/introducing/index.html | 281 +++++ .../javascript/asynchronous/promises/index.html | 589 ++++++++++ .../asynchronous/timeouts_and_intervals/index.html | 651 +++++++++++ .../build_your_own_function/index.html | 247 +++++ .../javascript/building_blocks/events/index.html | 588 ++++++++++ .../building_blocks/functions/index.html | 386 +++++++ .../he/learn/javascript/building_blocks/index.html | 51 + .../building_blocks/looping_code/index.html | 931 ++++++++++++++++ .../building_blocks/return_values/index.html | 180 ++++ .../index.html" | 789 ++++++++++++++ .../first_steps/a_first_splash/index.html | 634 +++++++++++ .../learn/javascript/first_steps/arrays/index.html | 564 ++++++++++ files/he/learn/javascript/first_steps/index.html | 64 ++ .../learn/javascript/first_steps/math/index.html | 427 ++++++++ .../first_steps/silly_story_generator/index.html | 139 +++ .../javascript/first_steps/strings/index.html | 172 +++ .../first_steps/useful_string_methods/index.html | 673 ++++++++++++ .../javascript/first_steps/variables/index.html | 333 ++++++ .../first_steps/what_is_javascript/index.html | 447 ++++++++ .../first_steps/what_went_wrong/index.html | 251 +++++ files/he/learn/javascript/index.html | 83 ++ .../adding_bouncing_balls_features/index.html | 214 ++++ .../he/learn/javascript/objects/basics/index.html | 257 +++++ files/he/learn/javascript/objects/index.html | 54 + .../javascript/objects/inheritance/index.html | 437 ++++++++ files/he/learn/javascript/objects/json/index.html | 346 ++++++ .../objects/object-oriented_js/index.html | 275 +++++ .../objects/object_prototypes/index.html | 283 +++++ .../he/learn/server-side/express_nodejs/index.html | 64 ++ .../express_nodejs/introduction/index.html | 542 ++++++++++ files/he/learn/server-side/index.html | 50 + files/he/mdn/community/index.html | 53 + files/he/mdn/contribute/getting_started/index.html | 131 +++ .../howto/create_an_mdn_account/index.html | 42 + files/he/mdn/contribute/howto/index.html | 18 + files/he/mdn/contribute/index.html | 66 ++ files/he/mdn/contribute/localize/index.html | 61 ++ .../localize/translating_pages/index.html | 73 ++ files/he/mdn/index.html | 18 + files/he/mozilla/add-ons/index.html | 104 ++ files/he/mozilla/add-ons/themes/index.html | 49 + .../add-ons/themes/theme_concepts/index.html | 248 +++++ .../anatomy_of_a_webextension/index.html | 144 +++ .../add-ons/webextensions/api/alarms/index.html | 60 ++ .../webextensions/api/browseraction/index.html | 124 +++ .../mozilla/add-ons/webextensions/api/index.html | 55 + .../add-ons/webextensions/api/storage/index.html | 102 ++ .../browser_support_for_javascript_apis/index.html | 24 + .../webextensions/content_scripts/index.html | 493 +++++++++ files/he/mozilla/add-ons/webextensions/index.html | 147 +++ .../manifest.json/background/index.html | 116 ++ .../add-ons/webextensions/manifest.json/index.html | 125 +++ .../index.html" | 198 ++++ .../webextensions/modify_a_web_page/index.html | 252 +++++ .../user_interface/browser_action/index.html | 51 + .../webextensions/user_interface/index.html | 97 ++ .../what_are_webextensions/index.html | 59 + .../your_first_webextension/index.html | 153 +++ .../your_second_webextension/index.html | 458 ++++++++ .../index.html" | 57 + files/he/mozilla/index.html | 10 + .../geometry.jsm/index.html | 20 + .../geometry.jsm/point/index.html | 264 +++++ .../he/mozilla/javascript_code_modules/index.html | 147 +++ files/he/mozilla/projects/index.html | 15 + files/he/mozilla/projects/rhino/index.html | 26 + .../thunderbird_localization/index.html | 98 ++ files/he/mozilla_mathml_project/index.html | 76 ++ files/he/mozilla_mathml_project/start/index.html | 77 ++ files/he/sandbox/index.html | 88 ++ files/he/web/api/console/index.html | 294 +++++ files/he/web/api/console/log/index.html | 39 + files/he/web/api/document/index.html | 488 +++++++++ files/he/web/api/document/write/index.html | 82 ++ files/he/web/api/domstring/index.html | 50 + files/he/web/api/element/index.html | 331 ++++++ files/he/web/api/geolocation/index.html | 109 ++ .../index.html" | 250 +++++ files/he/web/api/index.html | 38 + .../index.html | 141 +++ files/he/web/api/indexeddb_api/index.html | 165 +++ files/he/web/api/storage/clear/index.html | 52 + files/he/web/api/storage/getitem/index.html | 75 ++ files/he/web/api/storage/index.html | 107 ++ files/he/web/api/storage/key/index.html | 55 + files/he/web/api/storage/length/index.html | 51 + files/he/web/api/storage/removeitem/index.html | 66 ++ files/he/web/api/storage/setitem/index.html | 69 ++ files/he/web/api/web_storage_api/index.html | 111 ++ files/he/web/api/window/alert/index.html | 70 ++ files/he/web/api/window/confirm/index.html | 70 ++ files/he/web/api/window/index.html | 509 +++++++++ files/he/web/api/window/localstorage/index.html | 82 ++ files/he/web/api/window/prompt/index.html | 90 ++ files/he/web/api/xmlhttprequest/index.html | 172 +++ files/he/web/css/index.html | 97 ++ files/he/web/css/position/index.html | 274 +++++ files/he/web/guide/html/html5/index.html | 177 +++ files/he/web/guide/index.html | 62 ++ .../index.html | 62 ++ files/he/web/guide/performance/index.html | 23 + files/he/web/html/element/a/index.html | 90 ++ files/he/web/html/element/address/index.html | 77 ++ files/he/web/html/element/applet/index.html | 37 + files/he/web/html/element/article/index.html | 102 ++ files/he/web/html/element/aside/index.html | 75 ++ files/he/web/html/element/b/index.html | 68 ++ files/he/web/html/element/bdi/index.html | 60 ++ files/he/web/html/element/br/index.html | 62 ++ files/he/web/html/element/canvas/index.html | 70 ++ files/he/web/html/element/center/index.html | 104 ++ files/he/web/html/element/cite/index.html | 52 + files/he/web/html/element/del/index.html | 64 ++ files/he/web/html/element/em/index.html | 64 ++ files/he/web/html/element/figcaption/index.html | 67 ++ files/he/web/html/element/figure/index.html | 112 ++ files/he/web/html/element/font/index.html | 38 + files/he/web/html/element/footer/index.html | 62 ++ files/he/web/html/element/head/index.html | 68 ++ files/he/web/html/element/header/index.html | 72 ++ .../web/html/element/heading_elements/index.html | 77 ++ files/he/web/html/element/hgroup/index.html | 69 ++ files/he/web/html/element/hr/index.html | 74 ++ files/he/web/html/element/html/index.html | 59 + files/he/web/html/element/index.html | 105 ++ files/he/web/html/element/ins/index.html | 58 + files/he/web/html/element/main/index.html | 77 ++ files/he/web/html/element/mark/index.html | 86 ++ files/he/web/html/element/nav/index.html | 70 ++ files/he/web/html/element/p/index.html | 74 ++ files/he/web/html/element/section/index.html | 67 ++ files/he/web/html/element/strong/index.html | 69 ++ files/he/web/html/element/table/index.html | 162 +++ files/he/web/html/element/time/index.html | 93 ++ files/he/web/html/element/title/index.html | 61 ++ files/he/web/html/index.html | 108 ++ files/he/web/http/index.html | 91 ++ files/he/web/http/status/403/index.html | 55 + files/he/web/http/status/index.html | 197 ++++ files/he/web/hypertext_markup_language/index.html | 90 ++ files/he/web/index.html | 121 +++ files/he/web/javascript/guide/index.html | 125 +++ files/he/web/javascript/index.html | 97 ++ .../he/web/javascript/reference/errors/index.html | 31 + .../functions/default_parameters/index.html | 216 ++++ .../web/javascript/reference/functions/index.html | 596 ++++++++++ .../reference/global_objects/array/from/index.html | 243 +++++ .../global_objects/array/includes/index.html | 169 +++ .../reference/global_objects/array/index.html | 485 +++++++++ .../global_objects/array/unshift/index.html | 94 ++ .../javascript/reference/global_objects/index.html | 183 ++++ .../global_objects/object/assign/index.html | 272 +++++ .../reference/global_objects/object/index.html | 184 ++++ .../reference/global_objects/promise/index.html | 244 +++++ .../reference/global_objects/string/index.html | 314 ++++++ files/he/web/javascript/reference/index.html | 58 + .../operators/destructuring_assignment/index.html | 416 +++++++ .../web/javascript/reference/operators/index.html | 289 +++++ .../operators/operator_precedence/index.html | 330 ++++++ .../reference/statements/const/index.html | 133 +++ .../reference/statements/for...of/index.html | 269 +++++ .../reference/statements/for_each...in/index.html | 128 +++ .../reference/statements/function_star_/index.html | 212 ++++ .../web/javascript/reference/statements/index.html | 148 +++ .../reference/statements/return/index.html | 151 +++ .../javascript/reference/statements/var/index.html | 171 +++ files/he/web_development/index.html | 13 + .../index.html" | 10 + 191 files changed, 30821 insertions(+) create mode 100644 files/he/_redirects.txt create mode 100644 files/he/_wikihistory.json create mode 100644 files/he/archive/b2g_os/index.html create mode 100644 files/he/archive/index.html create mode 100644 files/he/dom/index.html create mode 100644 files/he/gecko_dom_reference/index.html create mode 100644 files/he/gecko_dom_reference/preface/index.html create mode 100644 files/he/glossary/css/index.html create mode 100644 files/he/glossary/html/index.html create mode 100644 files/he/glossary/index.html create mode 100644 "files/he/glossary/\327\236\327\242\327\250\327\232/index.html" create mode 100644 files/he/he/index.html create mode 100644 files/he/hebrew_localization/index.html create mode 100644 files/he/learn/css/index.html create mode 100644 files/he/learn/getting_started_with_the_web/index.html create mode 100644 files/he/learn/html/index.html create mode 100644 "files/he/learn/html/\327\230\327\221\327\234\327\220\327\225\327\252/index.html" create mode 100644 "files/he/learn/html/\327\230\327\244\327\241\327\231\327\235/index.html" create mode 100644 "files/he/learn/html/\327\236\327\221\327\225\327\220_\327\234\327\251\327\244\327\252_html/index.html" create mode 100644 "files/he/learn/html/\327\244\327\252\327\250\327\225\327\237_\327\221\327\242\327\231\327\225\327\252/index.html" create mode 100644 files/he/learn/index.html create mode 100644 files/he/learn/javascript/asynchronous/concepts/index.html create mode 100644 files/he/learn/javascript/asynchronous/index.html create mode 100644 files/he/learn/javascript/asynchronous/introducing/index.html create mode 100644 files/he/learn/javascript/asynchronous/promises/index.html create mode 100644 files/he/learn/javascript/asynchronous/timeouts_and_intervals/index.html create mode 100644 files/he/learn/javascript/building_blocks/build_your_own_function/index.html create mode 100644 files/he/learn/javascript/building_blocks/events/index.html create mode 100644 files/he/learn/javascript/building_blocks/functions/index.html create mode 100644 files/he/learn/javascript/building_blocks/index.html create mode 100644 files/he/learn/javascript/building_blocks/looping_code/index.html create mode 100644 files/he/learn/javascript/building_blocks/return_values/index.html create mode 100644 "files/he/learn/javascript/building_blocks/\327\252\327\240\327\220\327\231\327\235/index.html" create mode 100644 files/he/learn/javascript/first_steps/a_first_splash/index.html create mode 100644 files/he/learn/javascript/first_steps/arrays/index.html create mode 100644 files/he/learn/javascript/first_steps/index.html create mode 100644 files/he/learn/javascript/first_steps/math/index.html create mode 100644 files/he/learn/javascript/first_steps/silly_story_generator/index.html create mode 100644 files/he/learn/javascript/first_steps/strings/index.html create mode 100644 files/he/learn/javascript/first_steps/useful_string_methods/index.html create mode 100644 files/he/learn/javascript/first_steps/variables/index.html create mode 100644 files/he/learn/javascript/first_steps/what_is_javascript/index.html create mode 100644 files/he/learn/javascript/first_steps/what_went_wrong/index.html create mode 100644 files/he/learn/javascript/index.html create mode 100644 files/he/learn/javascript/objects/adding_bouncing_balls_features/index.html create mode 100644 files/he/learn/javascript/objects/basics/index.html create mode 100644 files/he/learn/javascript/objects/index.html create mode 100644 files/he/learn/javascript/objects/inheritance/index.html create mode 100644 files/he/learn/javascript/objects/json/index.html create mode 100644 files/he/learn/javascript/objects/object-oriented_js/index.html create mode 100644 files/he/learn/javascript/objects/object_prototypes/index.html create mode 100644 files/he/learn/server-side/express_nodejs/index.html create mode 100644 files/he/learn/server-side/express_nodejs/introduction/index.html create mode 100644 files/he/learn/server-side/index.html create mode 100644 files/he/mdn/community/index.html create mode 100644 files/he/mdn/contribute/getting_started/index.html create mode 100644 files/he/mdn/contribute/howto/create_an_mdn_account/index.html create mode 100644 files/he/mdn/contribute/howto/index.html create mode 100644 files/he/mdn/contribute/index.html create mode 100644 files/he/mdn/contribute/localize/index.html create mode 100644 files/he/mdn/contribute/localize/translating_pages/index.html create mode 100644 files/he/mdn/index.html create mode 100644 files/he/mozilla/add-ons/index.html create mode 100644 files/he/mozilla/add-ons/themes/index.html create mode 100644 files/he/mozilla/add-ons/themes/theme_concepts/index.html create mode 100644 files/he/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html create mode 100644 files/he/mozilla/add-ons/webextensions/api/alarms/index.html create mode 100644 files/he/mozilla/add-ons/webextensions/api/browseraction/index.html create mode 100644 files/he/mozilla/add-ons/webextensions/api/index.html create mode 100644 files/he/mozilla/add-ons/webextensions/api/storage/index.html create mode 100644 files/he/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html create mode 100644 files/he/mozilla/add-ons/webextensions/content_scripts/index.html create mode 100644 files/he/mozilla/add-ons/webextensions/index.html create mode 100644 files/he/mozilla/add-ons/webextensions/manifest.json/background/index.html create mode 100644 files/he/mozilla/add-ons/webextensions/manifest.json/index.html create mode 100644 "files/he/mozilla/add-ons/webextensions/manifest.json/\327\224\327\250\327\251\327\220\327\225\327\252/index.html" create mode 100644 files/he/mozilla/add-ons/webextensions/modify_a_web_page/index.html create mode 100644 files/he/mozilla/add-ons/webextensions/user_interface/browser_action/index.html create mode 100644 files/he/mozilla/add-ons/webextensions/user_interface/index.html create mode 100644 files/he/mozilla/add-ons/webextensions/what_are_webextensions/index.html create mode 100644 files/he/mozilla/add-ons/webextensions/your_first_webextension/index.html create mode 100644 files/he/mozilla/add-ons/webextensions/your_second_webextension/index.html create mode 100644 "files/he/mozilla/add-ons/webextensions/\327\230\327\231\327\244\327\225\327\235/index.html" create mode 100644 files/he/mozilla/index.html create mode 100644 files/he/mozilla/javascript_code_modules/geometry.jsm/index.html create mode 100644 files/he/mozilla/javascript_code_modules/geometry.jsm/point/index.html create mode 100644 files/he/mozilla/javascript_code_modules/index.html create mode 100644 files/he/mozilla/projects/index.html create mode 100644 files/he/mozilla/projects/rhino/index.html create mode 100644 files/he/mozilla/projects/thunderbird/thunderbird_localization/index.html create mode 100644 files/he/mozilla_mathml_project/index.html create mode 100644 files/he/mozilla_mathml_project/start/index.html create mode 100644 files/he/sandbox/index.html create mode 100644 files/he/web/api/console/index.html create mode 100644 files/he/web/api/console/log/index.html create mode 100644 files/he/web/api/document/index.html create mode 100644 files/he/web/api/document/write/index.html create mode 100644 files/he/web/api/domstring/index.html create mode 100644 files/he/web/api/element/index.html create mode 100644 files/he/web/api/geolocation/index.html create mode 100644 "files/he/web/api/geolocation/\327\236\327\236\327\251\327\247_\327\251\327\231\327\250\327\225\327\252\327\231_\327\236\327\231\327\247\327\225\327\235/index.html" create mode 100644 files/he/web/api/index.html create mode 100644 files/he/web/api/indexeddb_api/browser_storage_limits_and_eviction_criteria/index.html create mode 100644 files/he/web/api/indexeddb_api/index.html create mode 100644 files/he/web/api/storage/clear/index.html create mode 100644 files/he/web/api/storage/getitem/index.html create mode 100644 files/he/web/api/storage/index.html create mode 100644 files/he/web/api/storage/key/index.html create mode 100644 files/he/web/api/storage/length/index.html create mode 100644 files/he/web/api/storage/removeitem/index.html create mode 100644 files/he/web/api/storage/setitem/index.html create mode 100644 files/he/web/api/web_storage_api/index.html create mode 100644 files/he/web/api/window/alert/index.html create mode 100644 files/he/web/api/window/confirm/index.html create mode 100644 files/he/web/api/window/index.html create mode 100644 files/he/web/api/window/localstorage/index.html create mode 100644 files/he/web/api/window/prompt/index.html create mode 100644 files/he/web/api/xmlhttprequest/index.html create mode 100644 files/he/web/css/index.html create mode 100644 files/he/web/css/position/index.html create mode 100644 files/he/web/guide/html/html5/index.html create mode 100644 files/he/web/guide/index.html create mode 100644 files/he/web/guide/localizations_and_character_encodings/index.html create mode 100644 files/he/web/guide/performance/index.html create mode 100644 files/he/web/html/element/a/index.html create mode 100644 files/he/web/html/element/address/index.html create mode 100644 files/he/web/html/element/applet/index.html create mode 100644 files/he/web/html/element/article/index.html create mode 100644 files/he/web/html/element/aside/index.html create mode 100644 files/he/web/html/element/b/index.html create mode 100644 files/he/web/html/element/bdi/index.html create mode 100644 files/he/web/html/element/br/index.html create mode 100644 files/he/web/html/element/canvas/index.html create mode 100644 files/he/web/html/element/center/index.html create mode 100644 files/he/web/html/element/cite/index.html create mode 100644 files/he/web/html/element/del/index.html create mode 100644 files/he/web/html/element/em/index.html create mode 100644 files/he/web/html/element/figcaption/index.html create mode 100644 files/he/web/html/element/figure/index.html create mode 100644 files/he/web/html/element/font/index.html create mode 100644 files/he/web/html/element/footer/index.html create mode 100644 files/he/web/html/element/head/index.html create mode 100644 files/he/web/html/element/header/index.html create mode 100644 files/he/web/html/element/heading_elements/index.html create mode 100644 files/he/web/html/element/hgroup/index.html create mode 100644 files/he/web/html/element/hr/index.html create mode 100644 files/he/web/html/element/html/index.html create mode 100644 files/he/web/html/element/index.html create mode 100644 files/he/web/html/element/ins/index.html create mode 100644 files/he/web/html/element/main/index.html create mode 100644 files/he/web/html/element/mark/index.html create mode 100644 files/he/web/html/element/nav/index.html create mode 100644 files/he/web/html/element/p/index.html create mode 100644 files/he/web/html/element/section/index.html create mode 100644 files/he/web/html/element/strong/index.html create mode 100644 files/he/web/html/element/table/index.html create mode 100644 files/he/web/html/element/time/index.html create mode 100644 files/he/web/html/element/title/index.html create mode 100644 files/he/web/html/index.html create mode 100644 files/he/web/http/index.html create mode 100644 files/he/web/http/status/403/index.html create mode 100644 files/he/web/http/status/index.html create mode 100644 files/he/web/hypertext_markup_language/index.html create mode 100644 files/he/web/index.html create mode 100644 files/he/web/javascript/guide/index.html create mode 100644 files/he/web/javascript/index.html create mode 100644 files/he/web/javascript/reference/errors/index.html create mode 100644 files/he/web/javascript/reference/functions/default_parameters/index.html create mode 100644 files/he/web/javascript/reference/functions/index.html create mode 100644 files/he/web/javascript/reference/global_objects/array/from/index.html create mode 100644 files/he/web/javascript/reference/global_objects/array/includes/index.html create mode 100644 files/he/web/javascript/reference/global_objects/array/index.html create mode 100644 files/he/web/javascript/reference/global_objects/array/unshift/index.html create mode 100644 files/he/web/javascript/reference/global_objects/index.html create mode 100644 files/he/web/javascript/reference/global_objects/object/assign/index.html create mode 100644 files/he/web/javascript/reference/global_objects/object/index.html create mode 100644 files/he/web/javascript/reference/global_objects/promise/index.html create mode 100644 files/he/web/javascript/reference/global_objects/string/index.html create mode 100644 files/he/web/javascript/reference/index.html create mode 100644 files/he/web/javascript/reference/operators/destructuring_assignment/index.html create mode 100644 files/he/web/javascript/reference/operators/index.html create mode 100644 files/he/web/javascript/reference/operators/operator_precedence/index.html create mode 100644 files/he/web/javascript/reference/statements/const/index.html create mode 100644 files/he/web/javascript/reference/statements/for...of/index.html create mode 100644 files/he/web/javascript/reference/statements/for_each...in/index.html create mode 100644 files/he/web/javascript/reference/statements/function_star_/index.html create mode 100644 files/he/web/javascript/reference/statements/index.html create mode 100644 files/he/web/javascript/reference/statements/return/index.html create mode 100644 files/he/web/javascript/reference/statements/var/index.html create mode 100644 files/he/web_development/index.html create mode 100644 "files/he/\327\236\327\225\327\251\327\222\327\231\327\235/index.html" (limited to 'files/he') diff --git a/files/he/_redirects.txt b/files/he/_redirects.txt new file mode 100644 index 0000000000..d6435bd5b8 --- /dev/null +++ b/files/he/_redirects.txt @@ -0,0 +1,50 @@ +# FROM-URL TO-URL +/he/docs/HTML /he/docs/Web/HTML +/he/docs/HTML/Element /he/docs/Web/HTML/Element +/he/docs/HTML/Element/Heading_Elements /he/docs/Web/HTML/Element/Heading_Elements +/he/docs/HTML/Element/a /he/docs/Web/HTML/Element/a +/he/docs/HTML/Element/address /he/docs/Web/HTML/Element/address +/he/docs/HTML/Element/applet /he/docs/Web/HTML/Element/applet +/he/docs/HTML/Element/article /he/docs/Web/HTML/Element/article +/he/docs/HTML/Element/aside /he/docs/Web/HTML/Element/aside +/he/docs/HTML/Element/b /he/docs/Web/HTML/Element/b +/he/docs/HTML/Element/bdi /he/docs/Web/HTML/Element/bdi +/he/docs/HTML/Element/br /he/docs/Web/HTML/Element/br +/he/docs/HTML/Element/canvas /he/docs/Web/HTML/Element/canvas +/he/docs/HTML/Element/center /he/docs/Web/HTML/Element/center +/he/docs/HTML/Element/cite /he/docs/Web/HTML/Element/cite +/he/docs/HTML/Element/del /he/docs/Web/HTML/Element/del +/he/docs/HTML/Element/em /he/docs/Web/HTML/Element/em +/he/docs/HTML/Element/figcaption /he/docs/Web/HTML/Element/figcaption +/he/docs/HTML/Element/figure /he/docs/Web/HTML/Element/figure +/he/docs/HTML/Element/font /he/docs/Web/HTML/Element/font +/he/docs/HTML/Element/footer /he/docs/Web/HTML/Element/footer +/he/docs/HTML/Element/form /he/docs/Web/HTML/Element/form +/he/docs/HTML/Element/head /he/docs/Web/HTML/Element/head +/he/docs/HTML/Element/header /he/docs/Web/HTML/Element/header +/he/docs/HTML/Element/hgroup /he/docs/Web/HTML/Element/hgroup +/he/docs/HTML/Element/hr /he/docs/Web/HTML/Element/hr +/he/docs/HTML/Element/html /he/docs/Web/HTML/Element/html +/he/docs/HTML/Element/ins /he/docs/Web/HTML/Element/ins +/he/docs/HTML/Element/main /he/docs/Web/HTML/Element/main +/he/docs/HTML/Element/mark /he/docs/Web/HTML/Element/mark +/he/docs/HTML/Element/nav /he/docs/Web/HTML/Element/nav +/he/docs/HTML/Element/p /he/docs/Web/HTML/Element/p +/he/docs/HTML/Element/section /he/docs/Web/HTML/Element/section +/he/docs/HTML/Element/span /he/docs/Web/HTML/Element/span +/he/docs/HTML/Element/strong /he/docs/Web/HTML/Element/strong +/he/docs/HTML/Element/table /he/docs/Web/HTML/Element/table +/he/docs/HTML/Element/time /he/docs/Web/HTML/Element/time +/he/docs/HTML/Element/title /he/docs/Web/HTML/Element/title +/he/docs/JavaScript /he/docs/Web/JavaScript +/he/docs/JavaScript/%D7%AA%D7%99%D7%A2%D7%95%D7%93_JavaScript /he/docs/Web/JavaScript/%D7%AA%D7%99%D7%A2%D7%95%D7%93_JavaScript +/he/docs/JavaScript/%D7%AA%D7%99%D7%A2%D7%95%D7%93_JavaScript/%D7%90%D7%95%D7%91%D7%99%D7%99%D7%A7%D7%98%D7%99%D7%9D_%D7%92%D7%9C%D7%95%D7%91%D7%9C%D7%99%D7%99%D7%9D /he/docs/Web/JavaScript/%D7%AA%D7%99%D7%A2%D7%95%D7%93_JavaScript/%D7%90%D7%95%D7%91%D7%99%D7%99%D7%A7%D7%98%D7%99%D7%9D_%D7%92%D7%9C%D7%95%D7%91%D7%9C%D7%99%D7%99%D7%9D +/he/docs/JavaScript/%D7%AA%D7%99%D7%A2%D7%95%D7%93_JavaScript/%D7%90%D7%95%D7%91%D7%99%D7%99%D7%A7%D7%98%D7%99%D7%9D_%D7%92%D7%9C%D7%95%D7%91%D7%9C%D7%99%D7%99%D7%9D/Boolean /he/docs/Web/JavaScript/%D7%AA%D7%99%D7%A2%D7%95%D7%93_JavaScript/%D7%90%D7%95%D7%91%D7%99%D7%99%D7%A7%D7%98%D7%99%D7%9D_%D7%92%D7%9C%D7%95%D7%91%D7%9C%D7%99%D7%99%D7%9D/Boolean +/he/docs/JavaScript/%D7%AA%D7%99%D7%A2%D7%95%D7%93_JavaScript/%D7%90%D7%95%D7%91%D7%99%D7%99%D7%A7%D7%98%D7%99%D7%9D_%D7%92%D7%9C%D7%95%D7%91%D7%9C%D7%99%D7%99%D7%9D/Boolean/constructor /he/docs/Web/JavaScript/%D7%AA%D7%99%D7%A2%D7%95%D7%93_JavaScript/%D7%90%D7%95%D7%91%D7%99%D7%99%D7%A7%D7%98%D7%99%D7%9D_%D7%92%D7%9C%D7%95%D7%91%D7%9C%D7%99%D7%99%D7%9D/Boolean/constructor +/he/docs/JavaScript/%D7%AA%D7%99%D7%A2%D7%95%D7%93_JavaScript/%D7%90%D7%95%D7%91%D7%99%D7%99%D7%A7%D7%98%D7%99%D7%9D_%D7%92%D7%9C%D7%95%D7%91%D7%9C%D7%99%D7%99%D7%9D/Boolean/prototype /he/docs/Web/JavaScript/%D7%AA%D7%99%D7%A2%D7%95%D7%93_JavaScript/%D7%90%D7%95%D7%91%D7%99%D7%99%D7%A7%D7%98%D7%99%D7%9D_%D7%92%D7%9C%D7%95%D7%91%D7%9C%D7%99%D7%99%D7%9D/Boolean/prototype +/he/docs/JavaScript/%D7%AA%D7%99%D7%A2%D7%95%D7%93_JavaScript/%D7%90%D7%95%D7%91%D7%99%D7%99%D7%A7%D7%98%D7%99%D7%9D_%D7%92%D7%9C%D7%95%D7%91%D7%9C%D7%99%D7%99%D7%9D/Boolean/toSource /he/docs/Web/JavaScript/%D7%AA%D7%99%D7%A2%D7%95%D7%93_JavaScript/%D7%90%D7%95%D7%91%D7%99%D7%99%D7%A7%D7%98%D7%99%D7%9D_%D7%92%D7%9C%D7%95%D7%91%D7%9C%D7%99%D7%99%D7%9D/Boolean/toSource +/he/docs/MDN/Getting_started /he/docs/MDN/Contribute/Getting_started +/he/docs/Mozilla_MathML_Project/Start-redirect-1 /he/docs/Mozilla_MathML_Project/Start +/he/docs/Web/Guide/HTML /he/docs/Learn/HTML +/he/docs/Web/JavaScript/Reference/Methods_Index /he/docs/Web/JavaScript/Reference +/he/docs/en /en-US/ diff --git a/files/he/_wikihistory.json b/files/he/_wikihistory.json new file mode 100644 index 0000000000..37fee73fd8 --- /dev/null +++ b/files/he/_wikihistory.json @@ -0,0 +1,1136 @@ +{ + "DOM": { + "modified": "2019-01-16T14:20:09.020Z", + "contributors": [ + "ziv" + ] + }, + "Glossary": { + "modified": "2020-10-07T11:09:57.316Z", + "contributors": [ + "peterbe", + "chv", + "SphinxKnight", + "wbamberg", + "Sheppy" + ] + }, + "Glossary/CSS": { + "modified": "2019-03-18T21:25:53.823Z", + "contributors": [ + "haim" + ] + }, + "Glossary/HTML": { + "modified": "2020-10-01T06:50:13.204Z", + "contributors": [ + "chv" + ] + }, + "Glossary/מערך": { + "modified": "2019-04-14T20:37:05.958Z", + "contributors": [ + "MeirOverferst" + ] + }, + "Hebrew_Localization": { + "modified": "2019-01-16T14:19:44.573Z", + "contributors": [ + "ziv" + ] + }, + "Learn": { + "modified": "2020-07-16T22:43:41.705Z", + "contributors": [ + "meirlamdan", + "SphinxKnight", + "ItzikDabush", + "eternalStudent" + ] + }, + "Learn/CSS": { + "modified": "2020-07-16T22:25:33.951Z", + "contributors": [ + "TornadoIDS" + ] + }, + "Learn/Getting_started_with_the_web": { + "modified": "2020-07-16T22:33:52.646Z", + "contributors": [ + "ItzikDabush", + "fabio.rahamim", + "chrisdavidmills" + ] + }, + "Learn/HTML": { + "modified": "2020-07-16T22:22:17.538Z", + "contributors": [ + "RafeyIqbalRahman" + ] + }, + "Learn/HTML/טבלאות": { + "modified": "2020-07-16T22:25:11.770Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Learn/HTML/טפסים": { + "modified": "2020-07-16T22:20:57.218Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Learn/HTML/מבוא_לשפת_HTML": { + "modified": "2020-07-16T22:22:47.567Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Learn/HTML/פתרון_בעיות": { + "modified": "2020-07-16T22:22:28.745Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Learn/JavaScript": { + "modified": "2020-07-16T22:29:39.084Z", + "contributors": [ + "ItzikDabush", + "haim" + ] + }, + "Learn/JavaScript/Asynchronous": { + "modified": "2020-07-16T22:33:13.385Z", + "contributors": [ + "ItzikDabush" + ] + }, + "Learn/JavaScript/Asynchronous/Concepts": { + "modified": "2020-07-16T22:33:28.065Z", + "contributors": [ + "ItzikDabush" + ] + }, + "Learn/JavaScript/Asynchronous/Introducing": { + "modified": "2020-10-12T10:07:34.325Z", + "contributors": [ + "JonyCode", + "YOEL311", + "ItzikDabush" + ] + }, + "Learn/JavaScript/Asynchronous/Promises": { + "modified": "2020-07-16T22:33:23.960Z", + "contributors": [ + "ItzikDabush" + ] + }, + "Learn/JavaScript/Asynchronous/Timeouts_and_intervals": { + "modified": "2020-07-16T22:33:20.557Z", + "contributors": [ + "ItzikDabush" + ] + }, + "Learn/JavaScript/Building_blocks": { + "modified": "2020-07-16T22:31:08.087Z", + "contributors": [ + "ItzikDabush" + ] + }, + "Learn/JavaScript/Building_blocks/Build_your_own_function": { + "modified": "2020-07-19T21:11:05.221Z", + "contributors": [ + "meirlamdan", + "ItzikDabush" + ] + }, + "Learn/JavaScript/Building_blocks/Events": { + "modified": "2020-07-16T22:31:38.515Z", + "contributors": [ + "ItzikDabush" + ] + }, + "Learn/JavaScript/Building_blocks/Functions": { + "modified": "2020-07-19T20:25:49.052Z", + "contributors": [ + "meirlamdan", + "ItzikDabush" + ] + }, + "Learn/JavaScript/Building_blocks/Looping_code": { + "modified": "2020-07-16T22:31:19.721Z", + "contributors": [ + "ItzikDabush" + ] + }, + "Learn/JavaScript/Building_blocks/Return_values": { + "modified": "2020-07-16T22:31:33.541Z", + "contributors": [ + "ItzikDabush" + ] + }, + "Learn/JavaScript/Building_blocks/תנאים": { + "modified": "2020-07-16T22:31:13.828Z", + "contributors": [ + "ItzikDabush" + ] + }, + "Learn/JavaScript/First_steps": { + "modified": "2020-07-16T22:29:50.868Z", + "contributors": [ + "ItzikDabush", + "haim" + ] + }, + "Learn/JavaScript/First_steps/A_first_splash": { + "modified": "2020-07-16T22:30:18.220Z", + "contributors": [ + "ItzikDabush" + ] + }, + "Learn/JavaScript/First_steps/Arrays": { + "modified": "2020-07-16T22:30:54.818Z", + "contributors": [ + "ItzikDabush" + ] + }, + "Learn/JavaScript/First_steps/Math": { + "modified": "2020-07-16T22:30:25.401Z", + "contributors": [ + "ItzikDabush" + ] + }, + "Learn/JavaScript/First_steps/Silly_story_generator": { + "modified": "2020-07-16T22:31:01.708Z", + "contributors": [ + "meirlamdan", + "ItzikDabush" + ] + }, + "Learn/JavaScript/First_steps/Strings": { + "modified": "2020-07-16T22:30:39.658Z", + "contributors": [ + "ItzikDabush" + ] + }, + "Learn/JavaScript/First_steps/Useful_string_methods": { + "modified": "2020-07-16T22:30:47.396Z", + "contributors": [ + "ItzikDabush" + ] + }, + "Learn/JavaScript/First_steps/Variables": { + "modified": "2020-07-16T22:29:59.363Z", + "contributors": [ + "ItzikDabush" + ] + }, + "Learn/JavaScript/First_steps/What_is_JavaScript": { + "modified": "2020-07-16T22:30:07.974Z", + "contributors": [ + "ItzikDabush" + ] + }, + "Learn/JavaScript/First_steps/What_went_wrong": { + "modified": "2020-07-16T22:30:33.417Z", + "contributors": [ + "ItzikDabush" + ] + }, + "Learn/JavaScript/Objects": { + "modified": "2020-07-16T22:31:49.925Z", + "contributors": [ + "ItzikDabush" + ] + }, + "Learn/JavaScript/Objects/Adding_bouncing_balls_features": { + "modified": "2020-09-13T05:52:52.288Z", + "contributors": [ + "770camera" + ] + }, + "Learn/JavaScript/Objects/Basics": { + "modified": "2020-08-06T11:51:11.213Z", + "contributors": [ + "meirlamdan", + "ItzikDabush" + ] + }, + "Learn/JavaScript/Objects/Inheritance": { + "modified": "2020-07-16T22:32:14.216Z", + "contributors": [ + "Sheptus", + "ItzikDabush" + ] + }, + "Learn/JavaScript/Objects/JSON": { + "modified": "2020-07-16T22:32:25.717Z", + "contributors": [ + "ItzikDabush" + ] + }, + "Learn/JavaScript/Objects/Object-oriented_JS": { + "modified": "2020-08-06T15:32:42.627Z", + "contributors": [ + "meirlamdan", + "ItzikDabush" + ] + }, + "Learn/JavaScript/Objects/Object_prototypes": { + "modified": "2020-07-16T22:32:20.533Z", + "contributors": [ + "ItzikDabush" + ] + }, + "Learn/Server-side": { + "modified": "2020-07-16T22:35:57.571Z", + "contributors": [ + "meirlamdan" + ] + }, + "Learn/Server-side/Express_Nodejs": { + "modified": "2020-07-16T22:37:52.517Z", + "contributors": [ + "meirlamdan" + ] + }, + "Learn/Server-side/Express_Nodejs/Introduction": { + "modified": "2020-07-16T22:38:10.281Z", + "contributors": [ + "meirlamdan" + ] + }, + "MDN": { + "modified": "2019-03-23T22:50:58.746Z", + "contributors": [ + "wbamberg", + "Jeremie", + "eternalStudent" + ] + }, + "MDN/Community": { + "modified": "2019-09-11T08:02:56.848Z", + "contributors": [ + "SphinxKnight", + "dafbyte" + ] + }, + "MDN/Contribute": { + "modified": "2019-03-23T22:50:52.644Z", + "contributors": [ + "wbamberg", + "eternalStudent" + ] + }, + "MDN/Contribute/Getting_started": { + "modified": "2020-09-30T17:11:31.030Z", + "contributors": [ + "chrisdavidmills", + "ramiy", + "dafbyte", + "wbamberg", + "idoroiengel", + "eternalStudent" + ] + }, + "MDN/Contribute/Howto": { + "modified": "2020-12-07T19:29:58.920Z", + "contributors": [ + "ExE-Boss" + ] + }, + "MDN/Contribute/Howto/Create_an_MDN_account": { + "modified": "2019-03-18T21:21:11.313Z", + "contributors": [ + "dafbyte" + ] + }, + "MDN/Contribute/Localize": { + "modified": "2020-07-27T10:19:37.839Z", + "contributors": [ + "wbamberg" + ] + }, + "MDN/Contribute/Localize/Translating_pages": { + "modified": "2020-07-27T10:19:39.023Z", + "contributors": [ + "amir.bootbool" + ] + }, + "Mozilla": { + "modified": "2019-03-23T23:27:26.144Z", + "contributors": [ + "Sheppy" + ] + }, + "Mozilla/Add-ons": { + "modified": "2019-09-09T13:08:10.211Z", + "contributors": [ + "SphinxKnight", + "devinea2" + ] + }, + "Mozilla/Add-ons/WebExtensions": { + "modified": "2019-03-18T21:01:33.675Z", + "contributors": [ + "dafbyte" + ] + }, + "Mozilla/Add-ons/WebExtensions/API": { + "modified": "2020-06-25T04:51:40.197Z", + "contributors": [ + "AmitYaron", + "colbyhoward" + ] + }, + "Mozilla/Add-ons/WebExtensions/API/alarms": { + "modified": "2020-10-15T22:22:26.434Z", + "contributors": [ + "AmitYaron" + ] + }, + "Mozilla/Add-ons/WebExtensions/API/browserAction": { + "modified": "2020-10-15T22:30:57.985Z", + "contributors": [ + "AmitYaron" + ] + }, + "Mozilla/Add-ons/WebExtensions/API/storage": { + "modified": "2020-10-15T22:31:19.542Z", + "contributors": [ + "AmitYaron" + ] + }, + "Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension": { + "modified": "2019-11-18T15:08:05.989Z", + "contributors": [ + "AmitYaron" + ] + }, + "Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs": { + "modified": "2020-10-15T20:55:13.350Z", + "contributors": [ + "AmitYaron" + ] + }, + "Mozilla/Add-ons/WebExtensions/Content_scripts": { + "modified": "2019-08-29T10:24:19.189Z", + "contributors": [ + "AmitYaron" + ] + }, + "Mozilla/Add-ons/WebExtensions/Modify_a_web_page": { + "modified": "2020-07-03T08:40:42.413Z", + "contributors": [ + "AmitYaron" + ] + }, + "Mozilla/Add-ons/WebExtensions/What_are_WebExtensions": { + "modified": "2019-09-03T12:38:06.667Z", + "contributors": [ + "AmitYaron" + ] + }, + "Mozilla/Add-ons/WebExtensions/Your_first_WebExtension": { + "modified": "2019-08-29T10:20:28.270Z", + "contributors": [ + "AmitYaron" + ] + }, + "Mozilla/Add-ons/WebExtensions/Your_second_WebExtension": { + "modified": "2019-09-04T11:03:01.611Z", + "contributors": [ + "AmitYaron" + ] + }, + "Mozilla/Add-ons/WebExtensions/manifest.json": { + "modified": "2020-10-15T22:24:48.553Z", + "contributors": [ + "Zearin_Galaurum" + ] + }, + "Mozilla/Add-ons/WebExtensions/manifest.json/background": { + "modified": "2020-10-15T22:31:12.418Z", + "contributors": [ + "AmitYaron" + ] + }, + "Mozilla/Add-ons/WebExtensions/manifest.json/הרשאות": { + "modified": "2020-10-15T22:24:49.961Z", + "contributors": [ + "AmitYaron" + ] + }, + "Mozilla/Add-ons/WebExtensions/user_interface": { + "modified": "2020-06-25T06:33:52.755Z", + "contributors": [ + "chrisdavidmills" + ] + }, + "Mozilla/Add-ons/WebExtensions/user_interface/Browser_action": { + "modified": "2020-06-25T08:26:23.519Z", + "contributors": [ + "AmitYaron" + ] + }, + "Mozilla/Add-ons/WebExtensions/טיפום": { + "modified": "2019-08-30T04:55:04.968Z", + "contributors": [ + "AmitYaron" + ] + }, + "Web": { + "modified": "2019-03-23T23:14:11.445Z", + "contributors": [ + "dafbyte", + "fabio.rahamim", + "jsx", + "Yahpay", + "teoli" + ] + }, + "Web/API": { + "modified": "2020-10-03T08:46:15.865Z", + "contributors": [ + "amitbeck", + "Avrhamwales", + "teoli" + ] + }, + "Web/API/Console": { + "modified": "2020-10-15T22:10:17.991Z", + "contributors": [ + "irenesmith" + ] + }, + "Web/API/Console/log": { + "modified": "2020-10-15T22:10:17.607Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Web/API/DOMString": { + "modified": "2019-03-18T21:20:59.002Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Web/API/Document": { + "modified": "2020-10-15T22:09:48.432Z", + "contributors": [ + "Mlrobinson1993" + ] + }, + "Web/API/Document/write": { + "modified": "2020-10-15T22:09:32.825Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Web/API/Element": { + "modified": "2020-10-15T22:13:05.474Z", + "contributors": [ + "chrisdavidmills" + ] + }, + "Web/API/Geolocation": { + "modified": "2019-03-23T23:11:00.714Z", + "contributors": [ + "teoli" + ] + }, + "Web/API/Geolocation/ממשק_שירותי_מיקום": { + "modified": "2019-03-23T23:11:11.069Z", + "contributors": [ + "omeriko" + ] + }, + "Web/API/IndexedDB_API": { + "modified": "2019-11-29T09:18:23.722Z", + "contributors": [ + "LeonFrempong" + ] + }, + "Web/API/IndexedDB_API/Browser_storage_limits_and_eviction_criteria": { + "modified": "2020-06-18T08:34:41.680Z", + "contributors": [ + "AmitYaron" + ] + }, + "Web/API/Storage": { + "modified": "2020-10-15T22:12:12.917Z", + "contributors": [ + "gdg" + ] + }, + "Web/API/Storage/clear": { + "modified": "2020-10-15T22:12:24.951Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Web/API/Storage/getItem": { + "modified": "2020-10-15T22:12:25.257Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Web/API/Storage/key": { + "modified": "2020-10-15T22:12:24.812Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Web/API/Storage/length": { + "modified": "2020-10-15T22:12:25.024Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Web/API/Storage/removeItem": { + "modified": "2020-10-15T22:12:24.848Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Web/API/Storage/setItem": { + "modified": "2020-10-15T22:12:14.390Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Web/API/Web_Storage_API": { + "modified": "2020-10-15T22:31:39.589Z", + "contributors": [ + "AmitYaron" + ] + }, + "Web/API/Window": { + "modified": "2020-10-15T22:10:42.230Z", + "contributors": [ + "Sheppy" + ] + }, + "Web/API/Window/alert": { + "modified": "2020-10-15T22:10:26.250Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Web/API/Window/confirm": { + "modified": "2020-10-15T22:10:24.935Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Web/API/Window/localStorage": { + "modified": "2020-10-15T22:22:05.160Z", + "contributors": [ + "AmitYaron" + ] + }, + "Web/API/Window/prompt": { + "modified": "2020-10-15T22:10:19.323Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Web/API/XMLHttpRequest": { + "modified": "2020-10-15T22:12:48.713Z", + "contributors": [ + "fscholz", + "sideshowbarker" + ] + }, + "Web/CSS": { + "modified": "2019-09-11T03:12:30.829Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/CSS/position": { + "modified": "2020-10-15T22:08:31.453Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Web/Guide": { + "modified": "2019-03-23T23:05:01.546Z", + "contributors": [ + "dafbyte", + "apoorva" + ] + }, + "Web/Guide/HTML/HTML5": { + "modified": "2019-03-18T21:17:17.898Z", + "contributors": [ + "teoli", + "Windforce" + ] + }, + "Web/Guide/Localizations_and_character_encodings": { + "modified": "2019-08-29T10:26:50.778Z", + "contributors": [ + "AmitYaron" + ] + }, + "Web/Guide/Performance": { + "modified": "2019-03-18T21:18:07.307Z", + "contributors": [ + "dafbyte" + ] + }, + "Web/HTML": { + "modified": "2020-07-29T11:39:05.510Z", + "contributors": [ + "SphinxKnight" + ] + }, + "Web/HTML/Element": { + "modified": "2019-09-09T08:09:34.183Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim", + "teoli" + ] + }, + "Web/HTML/Element/Heading_Elements": { + "modified": "2019-09-09T08:09:34.951Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/a": { + "modified": "2019-09-09T08:09:31.251Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim", + "teoli", + "Inkbug" + ] + }, + "Web/HTML/Element/address": { + "modified": "2019-09-09T08:09:31.552Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/applet": { + "modified": "2019-09-09T08:09:52.174Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/article": { + "modified": "2019-09-09T08:09:34.507Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/aside": { + "modified": "2019-09-09T08:09:34.599Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/b": { + "modified": "2019-09-09T08:09:33.591Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/bdi": { + "modified": "2019-09-09T08:09:34.931Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/br": { + "modified": "2019-09-09T08:09:31.403Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/canvas": { + "modified": "2019-09-09T08:09:42.894Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/center": { + "modified": "2019-09-09T08:09:31.987Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/cite": { + "modified": "2019-09-09T08:09:41.537Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/del": { + "modified": "2019-09-09T08:09:33.548Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/em": { + "modified": "2019-09-09T08:09:48.199Z", + "contributors": [ + "SphinxKnight", + "idodana", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/figcaption": { + "modified": "2019-09-09T08:09:36.865Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/figure": { + "modified": "2019-09-09T08:09:45.693Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/font": { + "modified": "2019-09-09T08:09:47.343Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/footer": { + "modified": "2019-09-09T08:09:34.957Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/head": { + "modified": "2019-09-09T08:09:34.037Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/header": { + "modified": "2019-09-09T08:09:47.361Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/hgroup": { + "modified": "2019-09-09T08:09:33.606Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/hr": { + "modified": "2019-09-09T08:09:31.704Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/html": { + "modified": "2019-09-09T08:09:33.860Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/ins": { + "modified": "2019-09-09T08:09:34.404Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/main": { + "modified": "2019-09-09T08:09:36.292Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/mark": { + "modified": "2019-09-09T08:09:35.615Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/nav": { + "modified": "2019-09-09T08:09:35.863Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/p": { + "modified": "2019-09-09T08:09:31.599Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/section": { + "modified": "2019-09-09T08:09:37.847Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/strong": { + "modified": "2019-09-09T08:09:31.480Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/table": { + "modified": "2019-09-09T08:09:45.976Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/time": { + "modified": "2019-09-09T08:09:45.293Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTML/Element/title": { + "modified": "2019-09-09T08:09:31.348Z", + "contributors": [ + "SphinxKnight", + "fabio.rahamim" + ] + }, + "Web/HTTP": { + "modified": "2020-01-23T11:09:25.335Z", + "contributors": [ + "feifeili18" + ] + }, + "Web/HTTP/Status": { + "modified": "2020-10-15T22:26:35.107Z", + "contributors": [ + "adammatar" + ] + }, + "Web/HTTP/Status/403": { + "modified": "2020-11-18T16:02:55.271Z", + "contributors": [ + "chv" + ] + }, + "Web/Hypertext_Markup_Language": { + "modified": "2019-09-09T08:06:46.920Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Web/JavaScript": { + "modified": "2020-03-12T19:36:23.440Z", + "contributors": [ + "T882200", + "fabio.rahamim", + "fscholz", + "teoli", + "ziv" + ] + }, + "Web/JavaScript/Guide": { + "modified": "2020-03-12T19:42:40.958Z", + "contributors": [ + "x2357" + ] + }, + "Web/JavaScript/Reference": { + "modified": "2020-03-12T19:42:07.041Z", + "contributors": [ + "royGil", + "Minat" + ] + }, + "Web/JavaScript/Reference/Errors": { + "modified": "2020-03-12T19:45:07.364Z", + "contributors": [ + "Sheppy" + ] + }, + "Web/JavaScript/Reference/Functions": { + "modified": "2020-10-15T21:57:24.936Z", + "contributors": [ + "fabio.rahamim", + "fscholz" + ] + }, + "Web/JavaScript/Reference/Functions/Default_parameters": { + "modified": "2020-10-15T21:57:23.127Z", + "contributors": [ + "Reuven" + ] + }, + "Web/JavaScript/Reference/Global_Objects": { + "modified": "2020-03-12T19:42:41.419Z", + "contributors": [ + "fabio.rahamim", + "x2357" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Array": { + "modified": "2020-08-05T11:06:54.634Z", + "contributors": [ + "ariel.rotem1000", + "meirlamdan", + "MeirOverferst", + "kdex", + "ibratoev" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Array/from": { + "modified": "2020-10-15T22:17:20.213Z", + "contributors": [ + "Whose69", + "MeirOverferst" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Array/includes": { + "modified": "2019-03-23T22:26:42.843Z", + "contributors": [ + "Gal_Zakay" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Array/unshift": { + "modified": "2020-10-15T22:01:58.015Z", + "contributors": [ + "naomitayeb" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Object": { + "modified": "2020-10-15T22:12:27.578Z", + "contributors": [ + "fscholz" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Object/assign": { + "modified": "2020-11-10T06:21:37.336Z", + "contributors": [ + "dorheitner" + ] + }, + "Web/JavaScript/Reference/Global_Objects/Promise": { + "modified": "2020-10-15T22:12:11.929Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Web/JavaScript/Reference/Global_Objects/String": { + "modified": "2020-10-15T22:09:01.642Z", + "contributors": [ + "fabio.rahamim", + "HuangYuSan" + ] + }, + "Web/JavaScript/Reference/Operators": { + "modified": "2020-12-07T20:30:11.897Z", + "contributors": [ + "arai" + ] + }, + "Web/JavaScript/Reference/Operators/Destructuring_assignment": { + "modified": "2020-03-12T19:42:42.276Z", + "contributors": [ + "dafbyte", + "BlackB1RD", + "kdex", + "ShakedAmar" + ] + }, + "Web/JavaScript/Reference/Operators/Operator_Precedence": { + "modified": "2020-03-12T19:42:13.747Z", + "contributors": [ + "cobicarmel", + "jnfsmile" + ] + }, + "Web/JavaScript/Reference/Statements": { + "modified": "2020-03-12T19:42:34.939Z", + "contributors": [ + "royGil", + "Sebastianz" + ] + }, + "Web/JavaScript/Reference/Statements/const": { + "modified": "2020-10-15T22:11:57.477Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Web/JavaScript/Reference/Statements/for...of": { + "modified": "2020-03-12T19:44:55.627Z", + "contributors": [ + "morwin" + ] + }, + "Web/JavaScript/Reference/Statements/function*": { + "modified": "2020-10-15T22:12:13.549Z", + "contributors": [ + "dafbyte" + ] + }, + "Web/JavaScript/Reference/Statements/return": { + "modified": "2020-10-15T22:12:39.963Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Web/JavaScript/Reference/Statements/var": { + "modified": "2020-10-15T22:10:51.321Z", + "contributors": [ + "fabio.rahamim" + ] + }, + "Web_Development": { + "modified": "2019-01-16T14:20:09.744Z", + "contributors": [ + "ziv" + ] + }, + "he": { + "modified": "2019-03-24T00:06:58.385Z", + "contributors": [ + "ziv" + ] + }, + "מושגים": { + "modified": "2019-03-24T00:07:06.819Z", + "contributors": [ + "ziv" + ] + } +} \ No newline at end of file diff --git a/files/he/archive/b2g_os/index.html b/files/he/archive/b2g_os/index.html new file mode 100644 index 0000000000..ad0288a3a5 --- /dev/null +++ b/files/he/archive/b2g_os/index.html @@ -0,0 +1,75 @@ +--- +title: Firefox OS +slug: Archive/B2G_OS +translation_of: Archive/B2G_OS +--- +

Firefox OS (לעתים מקוצר כ-FxOS) היא מערכת הפעלה ניידת חדשה המפותחת על ידי Mozilla. היא משתמשת בקרנל לינוקס ומאתחלת למנוע ריצה מבוסס גקו, המאפשר למשתמשים להפעיל יישומים המפותחים בעזרת HTML,‏ JavaScript, ו-API פתוחים נוספים של המרשתת בלבד.

+ +

Firefox OS נמצאת בפיתוח מתמיד; אנו עובדים באופן קבוע על דרכים להפוך אותה קלה יותר לשימוש עבורך, ולפתח על גאיה (Gaia, אוסף היישומים בברירת המחדל) ולפתח יישומים משלך. עם זאת, אתה צריך ידע אודות מערכות על מנת לעשות דברים כמו לבנות את כל מערכת Firefox OS, או לטעון גרסה של Firefox OS על טלפון. להלן מקושרים מדריכים המיועדים למפתחי אינטרנט המעוניינים להריץ את גאיה או לבצע בה שינויים, או לפתח יישומים שיפעלו על מכשירי Firefox OS.

+ + + + + + + + +
+

תיעוד אודות Firefox OS

+ +
+
היכרות עם Firefox OS
+
מידע להיכרות אודות מהי Firefox OS וכיצד היא פועלת.
+
טיפים וטריקים עם Firefox OS
+
כמה מאמרים קצרים אודות עצות ותעלולים מועילים שכדאי לדעת על Firefox OS כאשר מפתחים אותה.
+
כתיבת יישומים עבור Firefox OS
+
תיעוד אודות יצירת יישומי Firefox OS.
+
מרכז המפתחים
+
אוסף כלים מדריכים ושרותים למפתחים של יישומי Firefox OS.
+
חווית משתמש
+
עיצוב ומדריכי חוויית משתמש - כמו גם תבניות ודוגמאות קוד - שיעזרו לך ליצור יישומים מושכים ועקביים עבור Firefox OS.
+
פלטפורמת Firefox OS
+
תיעוד אודות פלטפורמת Firefox OS, כולל  Gonk,‏ Gaia וכל מה שבאמצע. זה כולל תיעוד אודות בנייה והתקנה של המערכת על מכשירים, וכן בנייה של הסימולטור והאמולטורים.
+
אבטחה
+
תיעוד אודות אבטחה ב-Firefox OS; בכלל זה מאמרים אודות התקני אבטחה מכל נקודת מבט: עבור מפתחי יישומים, אינטגרטורים ועוד.
+
ביצועים
+
מאמרים אודות מיטוב יישומי Firefox OS.
+
איתור בעיות
+
מדריך לפתרון בעיות נפוצות עם Firefox OS.
+
ניפוי באגים ב-Firefox OS
+
מדריך לניפוי באגים הן ביישומים הניידים שלך וב-Firefox OS עצמה.
+
מדריך טלפוני פיתוח של Firefox OS
+
מדריך לטלפוני פיתוח של Firefox OS ש-Mozilla מספקת למפתחים מסויימים. מדריך זה תקף גם אם מישהו התקין את Firefox OS על הטלפון שלך עבורך.
+
+ +

הצג הכל...

+
+

קבלת עזרה מהקהילה

+ +

אם אתה עובד עם Firefox OS, או מפתח יישומים שברצונך שיפעלו על מכשירי Firefox OS, קיימים משאבים קהילתיים שיעזרו לך!

+ +
    +
  • שאל את שאלתך בערוץ ה-IRC של Mozilla של "אתחל אל Gecko": #b2g
  • +
+ +

אל תשכח את אתיקת האינטרנט...

+ + + + + + +

משאבים

+ + +
diff --git a/files/he/archive/index.html b/files/he/archive/index.html new file mode 100644 index 0000000000..7046fbc2b8 --- /dev/null +++ b/files/he/archive/index.html @@ -0,0 +1,20 @@ +--- +title: Archive of obsolete content +slug: Archive +translation_of: Archive +--- +

(he translation)

+ +

Here at MDN, we try to avoid outright deleting content that might be useful to people targeting legacy platforms, operating systems, and browsers. Perhaps your target audience is people that are using older hardware, for example, and can't upgrade to the latest and greatest browsers. Or for "reasons," your company is required to use very old software and you need to build Web content that runs on that software. Or perhaps you're just curious about the history of an obsolete feature or API, and how it worked.

+ +

There are many reasons older documentation can be useful. So, we've established this area into which we can archive older documentation. Material in this Archived content zone should not be used for building new Web sites or apps for modern browsers. It's here for historical reference only.

+ +
+

Note to writers: We need to try to keep the subpages here organized instead of all dumped into one large folder. Try to create subtrees for categories of material. Also, only move pages here that are extremely obsolete. If anyone might realistically need the information in a living product, it may not be appropriate to move it here. In general, it may be best to discuss it in the MDN Web Docs chat room before moving content here.

+
+ +

{{SubpagesWithSummaries}}

+ + + +

{{ListSubpages("/en-US/docs/Archive", 2, 0, 1)}}

diff --git a/files/he/dom/index.html b/files/he/dom/index.html new file mode 100644 index 0000000000..136335eb20 --- /dev/null +++ b/files/he/dom/index.html @@ -0,0 +1,13 @@ +--- +title: DOM +slug: DOM +--- +
+

 

+
+

Document Object Model הינו API עבור מסמכי HTML ו-XML. הוא מספק ייצוג מבני של המסמך המאפשר הן את שינוי תוכן המסמך ואת מראהו. עיקר תפקידו של ממשק זה, לאפשר לנו לחבר בין דפי אינטרנט לבין שפות תכנות.

+

תיעוד

+
Gecko DOM
The Gecko Document Object Model Reference.
+
+
+
diff --git a/files/he/gecko_dom_reference/index.html b/files/he/gecko_dom_reference/index.html new file mode 100644 index 0000000000..94dad96837 --- /dev/null +++ b/files/he/gecko_dom_reference/index.html @@ -0,0 +1,10 @@ +--- +title: Gecko DOM Reference +slug: Gecko_DOM_Reference +--- +
+

תוכן העניינים עבור Gecko DOM:

+ +

 

+
diff --git a/files/he/gecko_dom_reference/preface/index.html b/files/he/gecko_dom_reference/preface/index.html new file mode 100644 index 0000000000..b9ab0227ea --- /dev/null +++ b/files/he/gecko_dom_reference/preface/index.html @@ -0,0 +1,31 @@ +--- +title: Preface +slug: Gecko_DOM_Reference/Preface +--- +
+

מבוא

+

{{ ApiRef() }}

+

אודות מבוא זה

+

 חלק זה מתאר את המדריך עצמו, איך המידע בו מוצג ואיך אתה יכול להשתמש בדוגמאות המובאות במדריך זה בפיתוח ה-DOM שלך.

+

מסמך זה נמצא בפיתוח ותרגום מתמיד ואינו מכיל את כלל המידע אודות DOM.

+

מי צריך לקרא את המסמך הזה

+

הקורא של מדריך זה הוא מפתח אתרים או משתמש המבין בבניית אתרים ומבנה דפי אינטרנט. מדריך זה נמנע מהנחות מוקדמות אודות ההכרות של הקוראים עם DOM, עם XML, עם שרתי אינטרנט, עם תקינה הקשורה באינטרנט וגם עם JavaScript. מדריך זה יוצא מתוך הנחה שלקורא הכרות עם HTML ועם המבנה הבסיסי של דף אינטרנט, עם דפדפנים ועם CSS.

+

המידע המקדים המוצג במדריך זה, כמו גם המידע המתקדם הינו בעל ערך רב עבור מפתחי אינטרנט מנוסים ובלתי מנוסים כאחד, ואינו רק עבור המתחילים בפיתוח לאינטרנט.

+

מהוא Gecko?

+

מוזילה, Firefox, Netscape ושאר הדפדפנים מבוססי מוזילה משתמשים במימוש זהה של DOM.

+

Gecko, רכיב התכנה בדפדפנים המטפל בניתוח דפי HTML, מבנה הדפים, DOM ותצוגת ממשק התכנית עצמה - הינו מימוש של מנוע תצוגה מהיר ותואם התקינה של W3C ושל רכיבים דמויי DOM.

+

תחביר API

+

התיאורים במדריך זה של ה-API מכילים את התחביר, פרמטרים, דוגמאות, הערות וקישורים למפרטים המתאימים.

+

לרוב, מאפיינים לקריאה בלבד ישנה שורת תחביר אחת מאחר ואין אפשרות לשנות אותם, אלא רק לגשת (לקרא) אותם. לדוגמה, המאפיין לקריאה בלבד availHeight של אובייקט screen מכיל את המידע הבא אודות התחביר:

+
iAvail = window.screen.availHeight
+
+

במקרה זה, הכוונה היא שניתן להשתמש במאפיין רק בצידו הימני של הביטוי, לעומת מאפיין לקריאה וכתיבה, אותו ניתן גם לשנות כמו שמדגימה דוגמת התחביר הבאה:

+
msg = window.status
+window.status = msg
+
+

באופן כללי, כאשר אנו מתארים מאפיין של אובייקט, נציג את האובייקט בצורה פשוטה, כלומר element עבור כלל הרכיבים ו document עבור רכיב המסמך (document) הראשי.

+

שימוש בדוגמאות

+

דוגמאות רבות במדריך זה הינן תוכן של קבצים שלמים שניתן להריץ בצורה פשוטה על ידי העתקה והדבקה לקובץ חדש - ופתיחתם באמצעות דפדפן. דוגמאות אחרות הינן רק פיסות קוד, אותן ניתן להריץ על ידי עטיפתם בפונקצית JavaScript.

+

 

+
+

 

diff --git a/files/he/glossary/css/index.html b/files/he/glossary/css/index.html new file mode 100644 index 0000000000..cae8af060f --- /dev/null +++ b/files/he/glossary/css/index.html @@ -0,0 +1,50 @@ +--- +title: CSS +slug: Glossary/CSS +tags: + - CSS + - מילון מונחים + - קידוד סקריפטים +translation_of: Glossary/CSS +--- +

CSS (גליונות סגנון מדורגים {=Cascading Style Sheets}) הינה שפה הצהרתית אשר אחראית על איך יראה דף האינטרנט ב{{glossary("דפדפן")}}. הדפדפן מחיל את הצהרות הסגנון של הCSS על האלמנטים הנבחרים על מנת להציגם כראוי. הצהרת סגנון מכילה מאפיינים ואת הערכים שלהם, אשר קובעים איך ייראה דף האינטרנט.

+ +

CSS הינה אחת משלושת טכנולוגיות היסוד של האינטרנט, יחד עם {{Glossary("HTML")}} ו{{Glossary("JavaScript")}}. למעשה CSS מסגננת את האלמנטים של ה{{Glossary("Element","HTML")}}, אך יכולה לשמש גם שפת סיגנון לשפות תגיות אחרות כמו {{Glossary("SVG")}} או {{Glossary("XML")}}.

+ +

כלל CSSסי הינו מערכת של {{Glossary("מאפיין CSS","מאפיינים")}} המשוייכת ל{{Glossary("CSS selector", "סלקטור")}}. להלן דוגמא שצובעת כל פסקת HTML בצהוב על רקע שחור:

+ +
/* הסלקטור בשורה הבאה מצביע על כך שכל הפסיקות במסמך יושפעו מ'הכלל' הזה. */
+p {
+
+  /* המאפיין בשורה הבאה מגדיר את צבע הטקסט, במקרה הזה צהוב. */
+  color: yellow;
+
+  /* המאפיין בשורה הבאה מגדיר את צבע הרקע, במקרה הזה שחור. */
+  background-color: black
+}
+ +
 
+ +

"מדורגים" מתייחס לכלל שקובע לפי איזה סדר הסלקטורים יוכלו להביא את השינויים שלהם לסגנון הדף. זהו פיצ'ר מאוד נצרך, מכיוון שאתר מורכב יכול להכיל אלפים של כללי CSS.

+ +

למד עוד

+ +

ידע כללי

+ + + +

התייחסות טכנית

+ + + +

למד אודות CSS

+ + diff --git a/files/he/glossary/html/index.html b/files/he/glossary/html/index.html new file mode 100644 index 0000000000..c5064257d8 --- /dev/null +++ b/files/he/glossary/html/index.html @@ -0,0 +1,46 @@ +--- +title: HTML +slug: Glossary/HTML +translation_of: Glossary/HTML +--- +
{{QuickLinksWithSubpages("/he-IL/docs/Glossary")}}
+ +

HTML (קיצור של HyperText Markup Language) היא 'שפה תיאורית' המציינת את מבנה דף האינטרנט.

+ +

קצת היסטוריה

+ +

בשנת 1990, כחלק מחזונו של ה-{{Glossary("World Wide Web","Web")}}, טים ברנרס-לי הגדיר את המושג {{Glossary("hypertext")}}, לאחר שנה הגדיר זאת בעיקר באמצעות {{Glossary("SGML")}}. ה-{{Glossary("IETF")}} החל לציין רשמית HTML בשנת 1993, ואחרי כמה טיוטות שוחררה גרסה 2.0 בשנת 1995. בשנת 1994 ייסד ברנרס-לי את {{Glossary("W3C")}} כדי לפתח את ה-Web. בשנת 1996 השתלט W3C על עבודת ה-HTML ופרסם את המלצת ה-HTML 3.2 כעבור שנה. HTML 4.0 שוחרר בשנת 1999 והפך לסטנדרט {{Glossary("ISO")}} בשנת 2000.

+ +

באותה תקופה, W3C כמעט נטש את HTML לטובת {{Glossary("XHTML")}}, מה שהניע את הקמתה של קבוצה עצמאית שנקראת {{Glossary("WHATWG")}} ב-2004. תודות ל- WHATWG, העבודה על {{Glossary("HTML5")}} המשיכה: שני הארגונים פרסמו את הטיוטה הראשונה בשנת 2008 ואת התקן הסופי בשנת 2014.

+ +

קונספט ותחביר

+ +

מסמך HTML הוא מסמך טקסט רגיל שמאורגן ומחולק באמצעות {{Glossary("element","elements")}}. אלמנטים מוקפים בפתיחה וסגירה תואמים - "תגיות" {{Glossary("tag","tags")}}. כל תגית מתחילה ומסתיימת בסוגריים זוויתיים (<>). ישנם כמה תגיות ריקות או מבוטלות שלא יכולות לכלול טקסט כלשהו, ​​למשל {{htmlelement("img")}}.

+ +

אפשר להרחיב את תגיות ה-HTML עם {{Glossary("attribute","attributes")}}, המספקים מידע ותכונות נוספות, שמשפיעים על האופן בו הדפדפן מפרש את האלמנט:

+ +

Detail of the structure of an HTML element

+ +

קובץ HTML נשמר בדרך כלל עם סיומת htm. או html., המוגשת על ידי {{Glossary("Server","web server")}}, וניתנת לעיבוד והצגה על ידי כל {{Glossary("Browser","Web browser")}}.

+ +

למד עוד

+ +

ידע כללי

+ + + +

לימוד HTML

+ + + +

התייחסויות טכניות

+ + diff --git a/files/he/glossary/index.html b/files/he/glossary/index.html new file mode 100644 index 0000000000..da2d505248 --- /dev/null +++ b/files/he/glossary/index.html @@ -0,0 +1,48 @@ +--- +title: 'MDN Web Docs Glossary: Definitions of Web-related terms' +slug: Glossary +tags: + - Beginner + - Definitions + - Dictionary + - Glossary + - Index + - Landing + - NeedsTranslation + - Terminology + - TopicStub +translation_of: Glossary +--- +
{{LearnBox({"title":"Learn a new term:"})}}
+ +

טכנולוגיות האינטרנט מכילות רשימות ארוכות של ביטויים וקיצורים המשמשים לתיעוד ולכתיבת קוד. מילון מונחים זה מספק הגדרות של מילים וקיצורים שעליך לדעת כדי להבין ולפתח בהצלחה בעולם ה-Web.

+ +

מילון מונחים

+ +

{{GlossaryList({"split": "h3", "css": "multiColumnList"})}}

+ +

תורמים למילון המונחים

+ +

מילון מונחים זה הוא עבודה שאינה נגמרת בעיצומה. אתה יכול לעזור ולשפר על ידי כתיבת ערכים חדשים או על ידי עדכון ושיפור הערכים הקיימים. הדרך הקלה ביותר להתחיל היא ללחוץ על הקישור הבא או לבחור באחד מהתנאים המוצעים להלן.

+ +

הוסף ערך חדש למילון

+ +

{{GlossaryList({"terms":["at-rule", "ALPN", "Attack", "Byte-Order Mark", "client", "Character set", "cryptosystem", "debug", "digital signature", "execution", "flex-direction", "GLSL", "Interface", "Library", "Memory management", "routers", "Self-Executing Anonymous Function", "Stylesheet", "Vector image"], "filter": "notdefined", "css": "multiColumnList"})}}

+ +

אם אתה רוצה לדעת יותר כיצד לתרום למילון המונחים, בדוק דף המצב של תיעוד מילון המונחים.

+ +

ראה עוד

+ + + + diff --git "a/files/he/glossary/\327\236\327\242\327\250\327\232/index.html" "b/files/he/glossary/\327\236\327\242\327\250\327\232/index.html" new file mode 100644 index 0000000000..5dc44022de --- /dev/null +++ "b/files/he/glossary/\327\236\327\242\327\250\327\232/index.html" @@ -0,0 +1,42 @@ +--- +title: מערך +slug: Glossary/מערך +translation_of: Glossary/array +--- +

 

+ +
מערך הוא אוסף מסודר של ערכים (או "פרימיטיבים" או "אובייקטים" תלוי בשפה) כל פריט באוסף נקרא איבר.
+ +
משתמשים במערכים בכדי לאכסן ערכים מרובים במשתנה יחיד. בשונה ממשתנה(רגיל) שיוכל לאכסן ערך יחיד.
+ +
לכל איבר במערך יש מספר המוצמד אליו שנקרא אינדקס ,אשר מאפשר לך לגישה אליו.
+בג'אווה סקריפט המערכים מתחילים מאינדקס אפס ואפשר לשנות אותם על ידי שימוש במתודות(methods) שונות.
+ +
 
+ +
מערך בג'אווה סקריפט נראה כך:
+ +

 

+ +
var myArray = [1, 2, 3, 4];
+var catNamesArray = ["Danny", "Yossi", "Hila"];
+//מערך בג'אווה סקריפט יכול להכיל סוגים שונים של מידע כפי שמתואר מעל
+ +

 

+ +

 

+ +

Learn more

+ +

General knowledge

+ + + +

Technical reference

+ + diff --git a/files/he/he/index.html b/files/he/he/index.html new file mode 100644 index 0000000000..8445c2fdfe --- /dev/null +++ b/files/he/he/index.html @@ -0,0 +1,14 @@ +--- +title: MDN +slug: he +--- +
+

ברוכים הבאים לרשת המפתחים של מוזילה

+

MDN_1a_150x172.png זהו פרוייקט התרגום העברי למאמרי רשת המפתחים של מוזילה (לשעבר MDC).

+ +

מדריכים

פיתוח לאינטרנט
משאבים למפתחי אינטרנט.
נגישות
איך לפתח עבור משתמשים עם מוגבלויות.
תקינה באינטרנט
איך ומדוע להשתמש בתקני אינטרנט בפיתוח.
אבטחה
אודות אבטחה באינטרנט.

מסמכים נוספים

כלים

Firebug
דיבאגר לאתרי אינטרנט.
Dom Inspector
כלי לחקירה וסקירה של ה DOM.
כלים נוספים

תיעוד וסימוכין (reference)

HTML
שפת סימון, הטכנולוגיה שבליבה של האינטרנט.
CSS
גליונות עיצוב.
JavaScript
שפת תסריט המניעה אפליקציות אינטרנט מודרניות.
DOM
תבנית המסמך המתארת את מבנה דפי האינטרנט.
AJAX
תקשורת א-סינכרונית.

סימוכין נוספים

+

 

+

עברית ב-MDN

+ +
diff --git a/files/he/hebrew_localization/index.html b/files/he/hebrew_localization/index.html new file mode 100644 index 0000000000..6b20079e38 --- /dev/null +++ b/files/he/hebrew_localization/index.html @@ -0,0 +1,7 @@ +--- +title: Hebrew Localization +slug: Hebrew_Localization +--- +

Special Hebrew Templates

+

Instead of jsOverrides, use HEjsOverrides

+

Multilingual templates with Hebrew localization

diff --git a/files/he/learn/css/index.html b/files/he/learn/css/index.html new file mode 100644 index 0000000000..92e818ddb8 --- /dev/null +++ b/files/he/learn/css/index.html @@ -0,0 +1,64 @@ +--- +title: CSS +slug: Learn/CSS +tags: + - Beginner + - CSS + - CodingScripting + - Debugging + - Landing + - NeedsContent + - NeedsTranslation + - Topic + - TopicStub + - length + - specificity +translation_of: Learn/CSS +--- +
{{LearnSidebar}}
+ +

Cascading Stylesheets — or {{glossary("CSS")}} — is the first technology you should start learning after {{glossary("HTML")}}. Whereas HTML is used to define the structure and semantics of your content, CSS is used to style it and lay it out. So for example, you can use CSS to alter the font, color, size and spacing of your content, split it into multiple columns, or add animations and other decorative features.

+ +

Learning pathway

+ +

You should really learn the basics of HTML before attempting any CSS. We'd recommend that you work through our Introduction to HTML module first — you can then learn about:

+ + + +

We'd recommend that you learn HTML and CSS at the same time, moving back and forth between the two topics. This is because HTML is far more interesting with CSS, and you can't really learn CSS without knowing HTML.

+ +

Before starting this topic, you should also have at least basic familiarity with using computers, and using the Web passively (i.e. just looking at it, consuming the content.) You should have a basic work environment set up as detailed in Installing basic software, and understand how to create and manage files, as detailed in Dealing with files — both are parts of our Getting started with the web complete beginner's module.

+ +

It is recommended that you work through Getting started with the web before attempting this topic, however it isn't absolutely necessary; much of what is covered in the CSS basics article is also covered in our Introduction to CSS module, albeit in a lot more detail.

+ +

Modules

+ +

This topic contains the following modules, in a suggested order for working through them. You should definitely start with the first one.

+ +
+
Introduction to CSS
+
This module gets you started with the basics of how CSS works, including selectors and properties, writing CSS rules, applying CSS to HTML, how to specify length, color, and other units in CSS, cascade and inheritance, box model basics, and debugging CSS.
+
Styling text
+
Here we look at text styling fundamentals, including setting font, boldness, and italics, line and letter spacing, and drop shadows and other text features. We round off the module by looking at applying custom fonts to your page, and styling lists and links.
+
Styling boxes
+
Next up, we look at styling boxes, one of the fundamental steps towards laying out a web page. In this module we recap the box model then look at controlling box layouts by setting padding, borders and margins, setting custom background colors, images and other features, and fancy features such as drop shadows and filters on boxes.
+
CSS layout
+
At this point we've already looked at CSS fundamentals, how to style text, and how to style and manipulate the boxes that your content sits inside. Now it's time to look at how to place your boxes in the right place in relation to the viewport, and one another. We have covered the necessary prerequisites so you can now dive deep into CSS layout, looking at different display settings, traditional layout methods involving float and positioning, and new fangled layout tools like flexbox.
+
Responsive design (TBD)
+
With so many different types of devices able to browse the Web these days, responsive web design (RWD) has become a core web development skill. This module will cover the basic principles and tools of RWD, explain how to apply different CSS to a document depending on device features like screen width, orientation, and resolution, and explore the technologies available for serving different video and images depending on such features.
+
+ +

Solving common CSS problems

+ +

Use CSS to solve common problems provides links to sections of content explaining how to use CSS to solve very common problems when creating a webpage.

+ +

See also

+ +
+
CSS on MDN
+
The main entry point for CSS documentation on MDN, where you'll find detailed reference documentation for all features of the CSS language. Want to know all the values a property can take? This is a good place to go.
+
diff --git a/files/he/learn/getting_started_with_the_web/index.html b/files/he/learn/getting_started_with_the_web/index.html new file mode 100644 index 0000000000..b0c020b580 --- /dev/null +++ b/files/he/learn/getting_started_with_the_web/index.html @@ -0,0 +1,61 @@ +--- +title: תחילת הדרך עם ה-Web +slug: Learn/Getting_started_with_the_web +tags: + - Beginner + - CSS + - Design + - Guide + - HTML + - Index + - NeedsTranslation + - TopicStub + - 'l10n:priority' + - publishing + - theory +translation_of: Learn/Getting_started_with_the_web +--- +
{{LearnSidebar}}
+ +
+

Getting started with the Web is a concise series introducing you to the practicalities of web development. You'll set up the tools you need to construct a simple webpage and publish your own simple code.

+
+ +

The story of your first website

+ +

It's a lot of work to create a professional website, so if you're new to web development we encourage you to start small. You won't build another Facebook right away, but it's not hard to get your own simple website online, so we'll start there.

+ +

By working through the articles listed below in order, you will go from nothing to getting your first webpage online. Let's go!

+ +

התקנת תוכנות בסיסיות

+ +

When it comes to tools for building a website, there's a lot to pick from. If you're just starting out, you might be confused by the array of code editors, frameworks, and testing tools out there. In Installing basic software we show you step-by-step how to install just the software you need to begin some basic web development.

+ +

עיצוב ונראות

+ +

מומלץ לתכנן את אתר האינטרנט לפני בנייתו, יש להכיר את הקווים המנחים שלו כגון: גודל הבאנרים, היכן ימוקם הלוגו? מהו הגובה המתאים, גופן, צבעים ועוד.

+ +

התמודדות עם קבצים

+ +

A website consists of many files: text content, code, stylesheets, media content, and so on. When you're building a website, you need to assemble these files into a sensible structure and make sure they can talk to one another. Dealing with files explains how to set up a sensible file structure for your website and what issues you should be aware of.

+ +

היכרות עם HTML

+ +

שפת HTML היא שפת תגיות המשמשת לבניה, עיצוב ועריכה של דפי אינטרנט.
+ זוהי שפה פשוטה לכתיבה ובאמצעותה ניתן להוסיף אל דף האינטרנט אלמנטים שונים כגון: טבלה, תמונות, קישורים, פסקאות ועוד.

+ +

היכרות עם CSS

+ +

Cascading Stylesheets (CSS) is the code that you use to style your website. For example, do you want the text to be black or red? Where should content be drawn on the screen? What background images and colors should be used to decorate your website? CSS basics takes you through what you need to get started.

+ +

היכרות עם Javascript

+ +

JavaScript is the programming language that you use to add interactive features to your website — for example: games, things that happen when buttons are pressed or data is entered in forms, dynamic styling effects, animation, and much more. JavaScript basics gives you an idea of what is possible with this exciting language, and how to get started.

+ +

פרסום האתר

+ +

כעת, לאחר שהקוד מוכן וכל קבצי האתר מאורגנים כל שנותר הוא להעלות אותו לאינטרנט כדי שכולם יוכלו לבקר בו, ראה מאמר זה המסביר כיצד לפרסם את האתר.

+ +

כיצד פועל האינטרנט?

+ +

מה קורה ברקע לאחר שאנחנו נכנסים לאתר האהוב עלינו? כיצד הנתונים מגיעים מהשרת והיכן הם מאוחסנים?

diff --git a/files/he/learn/html/index.html b/files/he/learn/html/index.html new file mode 100644 index 0000000000..df97989e28 --- /dev/null +++ b/files/he/learn/html/index.html @@ -0,0 +1,58 @@ +--- +title: 'Learning HTML: Guides and tutorials' +slug: Learn/HTML +tags: + - Beginner + - Guide + - HTML + - Intro + - Learn + - NeedsTranslation + - Topic + - TopicStub +translation_of: Learn/HTML +--- +
{{LearnSidebar}}
+ +

To build websites, you should know about {{Glossary('HTML')}} — the fundamental technology used to define the structure of a webpage. HTML is used to specify whether your web content should be recognized as a paragraph, list, heading, link, image, multimedia player, form, or one of many other available elements or even a new element that you define.

+ +

Learning pathway

+ +

Ideally, you should start your learning journey by learning HTML. Start by reading Introduction to HTML. You may then move on to learning about more advanced topics such as:

+ + + +

Before starting this topic, you should have at least basic familiarity with using computers and using the web passively (i.e. just looking at it, consuming the content). You should have a basic work environment set up as detailed in Installing basic software, and understand how to create and manage files, as detailed in Dealing with files — both are parts of our Getting started with the web complete beginner's module.

+ +

It is recommended that you work through Getting started with the web before attempting this topic, however, it isn't absolutely necessary; much of what is covered in the HTML basics article is also covered in our Introduction to HTML module, albeit in a lot more detail.

+ +

Modules

+ +

This topic contains the following modules, in a suggested order for working through them. You should definitely start with the first one.

+ +
+
Introduction to HTML
+
This module sets the stage, getting you used to important concepts and syntax, looking at applying HTML to text, how to create hyperlinks, and how to use HTML to structure a webpage.
+
Multimedia and embedding
+
This module explores how to use HTML to include multimedia in your web pages, including the different ways that images can be included, and how to embed video, audio, and even entire other webpages.
+
HTML Tables
+
Representing tabular data on a webpage in an understandable, {{glossary("Accessibility", "accessible")}} way can be a challenge. This module covers basic table markup, along with more complex features such as implementing captions and summaries.
+
HTML Forms
+
Forms are a very important part of the Web — these provide much of the functionality you need for interacting with websites, e.g. registering and logging in, sending feedback, buying products, and more. This module gets you started with creating the client-side parts of forms.
+
+ +

Solving common HTML problems

+ +

Use HTML to solve common problems provides links to sections of content explaining how to use HTML to solve very common problems when creating a webpage: dealing with titles, adding images or videos, emphasizing content, creating a basic form, etc.

+ +

See also

+ +
+
+
HTML (HyperText Markup Language) on MDN
+
The main entry point for HTML documentation on MDN, including detailed element and attribute references — if you want to know what attributes an element has or what values an attribute has, for example, this is a great place to start.
+
+
diff --git "a/files/he/learn/html/\327\230\327\221\327\234\327\220\327\225\327\252/index.html" "b/files/he/learn/html/\327\230\327\221\327\234\327\220\327\225\327\252/index.html" new file mode 100644 index 0000000000..8882fff3a0 --- /dev/null +++ "b/files/he/learn/html/\327\230\327\221\327\234\327\220\327\225\327\252/index.html" @@ -0,0 +1,34 @@ +--- +title: טבלאות HTML +slug: Learn/HTML/טבלאות +translation_of: Learn/HTML/Tables +--- +
{{LearnSidebar}}
+ +

A very common task in HTML is structuring tabular data, and it has a number of elements and attributes for just this purpose. Coupled with a little CSS for styling, HTML makes it easy to display tables of information on the web such as your school lesson plan, the timetable at your local swimming pool, or statistics about your favorite dinosaurs or football team. This module takes you through all you need to know about structuring tabular data using HTML.

+ +

Prerequisites

+ +

Before starting this module, you should already have covered the basics of HTML — see Introduction to HTML.

+ +
+

Note: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Thimble.

+
+ +

Guides

+ +

This module contains the following articles:

+ +
+
HTML table basics
+
This article gets you started with HTML tables, covering the very basics such as rows and cells, headings, making cells span multiple columns and rows, and how to group together all the cells in a column for styling purposes.
+
HTML table advanced features and accessibility
+
In the second article in this module, we look at some more advanced features of HTML tables — such as captions/summaries and grouping your rows into table head, body and footer sections — as well as looking at the accessibility of tables for visually impaired users.
+
+ +

Assessments

+ +
+
Structuring planet data
+
In our table assessment, we provide you with some data on the planets in our solar system, and get you to structure it into an HTML table.
+
diff --git "a/files/he/learn/html/\327\230\327\244\327\241\327\231\327\235/index.html" "b/files/he/learn/html/\327\230\327\244\327\241\327\231\327\235/index.html" new file mode 100644 index 0000000000..87fe398bc4 --- /dev/null +++ "b/files/he/learn/html/\327\230\327\244\327\241\327\231\327\235/index.html" @@ -0,0 +1,72 @@ +--- +title: טפסי HTML +slug: Learn/HTML/טפסים +translation_of: Learn/Forms +--- +
{{LearnSidebar}}
+ +

This module provides a series of articles that will help you master HTML forms. HTML forms are a very powerful tool for interacting with users; however, for historical and technical reasons, it's not always obvious how to use them to their full potential. In this guide, we'll cover all aspects of HTML forms, from structure to styling, from data handling to custom widgets.

+ +

Prerequisites

+ +

Before starting this module, you should at least work through our Introduction to HTML. At this point you should find the {{anch("Basic guides")}} easy to understand, and also be able to make use of our Native form widgets guide.

+ +

The rest of the module however is a bit more advanced — it is easy to put form widgets on a page, but you can't actually do much with them without using some advanced form features, CSS, and JavaScript. Therefore, before you look at the other sections we'd recommend that you go away and learn some CSS and JavaScript first.

+ +
+

Note: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Thimble.

+
+ +

Basic guides

+ +
+
Your first HTML form
+
The first article in our series provides your very first experience of creating an HTML form, including designing a simple form, implementing it using the right HTML elements, adding some very simple styling via CSS, and how data is sent to a server.
+
How to structure an HTML form
+
With the basics out of the way, we now look in more detail at the elements used to provide structure and meaning to the different parts of a form.
+
+ +

What form widgets are available?

+ +
+
The native form widgets
+
We now look at the functionality of the different form widgets in detail, looking at what options are available to collect different types of data.
+
+ +

Validating and submitting form data

+ +
+
Sending form data
+
This article looks at what happens when a user submits a form — where does the data go, and how do we handle it when it gets there? We also look at some of the security concerns associated with sending form data.
+
Form data validation
+
Sending data is not enough — we also need to make sure that the data users fill out in forms is in the correct format we need to process it successfully, and that it won't break our applications. We also want to help our users to fill out our forms correctly and don't get frustrated when trying to use our apps. Form validation helps us achieve these goals — this article tells you what you need to know.
+
+ +

Advanced guides

+ +
+
How to build custom form widgets
+
You'll come across some cases where the native form widgets just don't provide what you need, e.g. because of styling or functionality. In such cases, you may need to build your own form widget out of raw HTML. This article explains how you'd do this and the considerations you need to be aware of when doing so, with a practical case study.
+
Sending forms through JavaScript
+
This article looks at ways to use a form to assemble an HTTP request and send it via custom JavaScript, rather than standard form submission. It also looks at why you'd want to do this, and the implications of doing so. (See also Using FormData objects.)
+
HTML forms in legacy browsers
+
Article covering feature detection, etc. This should be redirected to the cross browser testing module, as the same stuff is covered better there.
+
+ +

Form styling guides

+ +
+
Styling HTML forms
+
This article provides an introduction to styling forms with CSS, including all the basics you might need to know for basic styling tasks.
+
Advanced styling for HTML forms
+
Here we look at some more advanced form styling techniques that need to be used when trying to deal with some of the more difficult-to-style elements.
+
Property compatibility table for form widgets
+
This last article provides a handy reference allowing you to look up what CSS properties are compatible with what form elements.
+
+ +

See also

+ + diff --git "a/files/he/learn/html/\327\236\327\221\327\225\327\220_\327\234\327\251\327\244\327\252_html/index.html" "b/files/he/learn/html/\327\236\327\221\327\225\327\220_\327\234\327\251\327\244\327\252_html/index.html" new file mode 100644 index 0000000000..4af3b86da6 --- /dev/null +++ "b/files/he/learn/html/\327\236\327\221\327\225\327\220_\327\234\327\251\327\244\327\252_html/index.html" @@ -0,0 +1,55 @@ +--- +title: מבוא לשפת HTML +slug: Learn/HTML/מבוא_לשפת_HTML +translation_of: Learn/HTML/Introduction_to_HTML +--- +
{{LearnSidebar}}
+ +

At its heart, {{glossary("HTML")}} is a fairly simple language made up of elements, which can be applied to pieces of text to give them different meaning in a document (Is it a paragraph? Is it a bulleted list? Is it part of a table?), structure a document into logical sections (Does it have a header? Three columns of content? A navigation menu?), and embed content such as images and videos into a page. This module will introduce the first two of these, and introduce fundamental concepts and syntax you need to know to understand HTML.

+ +

Prerequisites

+ +

Before starting this module, you don't need any previous HTML knowledge, but you should have at least basic familiarity with using computers and using the web passively (i.e., just looking at it and consuming content). You should have a basic work environment set up (as detailed in Installing basic software), and understand how to create and manage files (as detailed in Dealing with files). Both are parts of our Getting started with the web complete beginner's module.

+ +
+

Note: If you are working on a computer/tablet/other device that doesn't let you create your own files, you can try out (most of) the code examples in an online coding program such as JSBin or Thimble.

+
+ +

Guides

+ +

This module contains the following articles, which will take you through all the basic theory of HTML and provide ample opportunity for you to test out some skills.

+ +
+
Getting started with HTML
+
Covers the absolute basics of HTML, to get you started — we define elements, attributes, and other important terms, and show where they fit in the language. We also show how a typical HTML page is structured and how an HTML element is structured, and explain other important basic language features. Along the way, we'll play with some HTML to get you interested!
+
What’s in the head? Metadata in HTML
+
The head of an HTML document is the part that is not displayed in the web browser when the page is loaded. It contains information such as the page {{htmlelement("title")}}, links to {{glossary("CSS")}} (if you want to style your HTML content with CSS), links to custom favicons, and metadata (data about the HTML, such as who wrote it, and important keywords that describe the document).
+
HTML text fundamentals
+
One of HTML's main jobs is to give text meaning (also known as semantics), so that the browser knows how to display it correctly. This article looks at how to use HTML to break up a block of text into a structure of headings and paragraphs, add emphasis/importance to words, create lists, and more.
+
Creating hyperlinks
+
Hyperlinks are really important — they are what makes the web a web. This article shows the syntax required to make a link, and discusses best practices for links.
+
Advanced text formatting
+
There are many other elements in HTML for formatting text that we didn't get to in the HTML text fundamentals article. The elements in here are less well-known, but still useful to know about. In this article you'll learn about marking up quotations, description lists, computer code and other related text, subscript and superscript, contact information, and more.
+
Document and website structure
+
As well as defining individual parts of your page (such as "a paragraph" or "an image"), HTML is also used to define areas of your website (such as "the header," "the navigation menu," or "the main content column.") This article looks into how to plan a basic website structure and how to write the HTML to represent this structure.
+
Debugging HTML
+
Writing HTML is fine, but what if something goes wrong, and you can't work out where the error in the code is? This article will introduce you to some tools that can help.
+
+ +

Assessments

+ +

The following assessments will test your understanding of the HTML basics covered in the guides above.

+ +
+
Marking up a letter
+
We all learn to write a letter sooner or later; it is also a useful example to test out text formatting skills. In this assessment you'll be given a letter to mark up.
+
Structuring a page of content
+
This assessment tests your ability to use HTML to structure a simple page of content, containing a header, a footer, a navigation menu, main content, and a sidebar.
+
+ +

See also

+ +
+
Web literacy basics 1
+
An excellent Mozilla foundation course that explores and tests a lot of the skills talked about in the Introduction to HTML module. Learners get familiar with reading, writing, and participating on the web in this six-part module. Discover the foundations of the web through production and collaboration.
+
diff --git "a/files/he/learn/html/\327\244\327\252\327\250\327\225\327\237_\327\221\327\242\327\231\327\225\327\252/index.html" "b/files/he/learn/html/\327\244\327\252\327\250\327\225\327\237_\327\221\327\242\327\231\327\225\327\252/index.html" new file mode 100644 index 0000000000..d136f6d552 --- /dev/null +++ "b/files/he/learn/html/\327\244\327\252\327\250\327\225\327\237_\327\221\327\242\327\231\327\225\327\252/index.html" @@ -0,0 +1,141 @@ +--- +title: השתמש ב-HTML כדי לפתור בעיות נפוצות +slug: Learn/HTML/פתרון_בעיות +translation_of: Learn/HTML/Howto +--- +
{{LearnSidebar}}
+ +

The following links point to solutions to common everyday problems you'll need to solve with HTML.

+ +
+
+

Basic structure

+ +

The most basic application of HTML is document structure. If you're new to HTML you should start with this.

+ + + +

Basic text-level semantics

+ +

HTML specializes in providing semantic information for a document, so HTML answers many questions you might have about how to get your message across best in your document.

+ + +
+ +
+ + +

One of the main reasons for HTML is make navigation easy with {{Glossary("hyperlink", "hyperlinks")}}, which can be used in many different ways:

+ + + +

Images & multimedia

+ + + +

Scripting & styling

+ +

HTML only sets up document structure. To solve presentation issues, use {{glossary("CSS")}}, or use scripting to make your page interactive.

+ + + +

Embedded content

+ + +
+
+ +

Uncommon or advanced problems

+ +

Beyond the basics, HTML is very rich and offers advanced features for solving complex problems. These articles help you tackle the less common use cases you may face:

+ +
+
+

Forms

+ +

Forms are a complex HTML structure made to send data from a webpage to a web server. We encourage you to go over our full dedicated guide. Here is where you should start:

+ + + +

Tabular information

+ +

Some information, called tabular data, needs to be organized into tables with columns and rows. It's one of the most complex HTML structures, and mastering it is not easy:

+ + + +

Data representation

+ + +
+ + +
+ +

     

diff --git a/files/he/learn/index.html b/files/he/learn/index.html new file mode 100644 index 0000000000..792ffac056 --- /dev/null +++ b/files/he/learn/index.html @@ -0,0 +1,98 @@ +--- +title: מדריך Web Development +slug: Learn +translation_of: Learn +--- +
+

ברוכים הבאים לאזור הלמידה של MDN. קבוצה זו של מאמרים שואפת לספק לאנשים חסרי רקע בתכנות את הכלים הדרושים על מנת להתחיל לפתח אתרי אינטרנט ויישומי אינטרנט..

+ +

מטרתו של אזור זה של MDN היא לא לקחת אתכם מ-"מתחילים" -"מומחה" אלא לקחת אתכם מ-"מתחילים" ל"נוח". משם אתם אמורים להיות מסוגלים להתקדם בכוחות עצמכם, ללמוד מיתר התכנים באתר שלנו ובאתרים אחרים.

+ +

אם אתם חסרי רקע לחלוטין בתכנות חשוב להבין ש-web development יכול להיות מאתגר - אנו נסייע כמה שניתן על מנת לספק מספיק פרטים כדי שתוכלו להרגיש בנוח וללמוד את הנושאים כראוי.

+
+ +
+

חשוב: התוכן באיזור הלמידה מתעדכן באופן שוטף. אם יש לכם שאלות בנוגע לנושאים שאנו דנים בהם או שתרצו שנוסיף נושאים חדשים, הרגישו חופשי ליצור עמנו קשר ב {{anch("Contact us")}}

+
+ +

היכן להתחיל?

+ +

אנחנו רוצים לפגוש אותך היכן שאתה נמצא. מה מהתיאורים הבאים מתאים לך יותר?

+ + + +
+

הערה: המילון שלנו מכיל הסבר לכל מונח וביטוי. נסו להפיק ממנו את המירב.

+
+ +

{{LearnBox({"title":"Random glossary entry"})}}

+ +

נושאי הלימוד

+ +

אלו הנושאים שנגע בהם באיזור הלימוד של MDN:

+ +
+
תחילת הדרך עם ה-Web
+
מספק הכרות בסיסית ומעשית לפיתוח אינטרנט עבור מתחילים וחסרי רקע.
+
HTML - בונים את האינטרנט 
+
HTML זו השפה שבה אנחנו משתמשים על מנת לתת מבנה לתוכן שלנו ולהגדיר מה המשמעות שלהם או מטרתם. נושא זה מלמד את שפת HTML לעומק.  
+
CSS - מעצבים את האינטרנט
+
CSS היא השפה שאנחנו משתמשים בה על מנת לעצב את התוכן שלנו ועל מנת לפרוס את התוכן שלנו באתר, כמו גם להוסיף הנפשות ואנימציות שונות. נושא זה מלמד היבטים רבים של שפת CSS והכלים העומדים לרשותנו. 
+
JavaScript - תכנות צד לקוח 
+
JavaScript היא שפת תכנות דינאמית אשר משמשת על מנת להוסיף פונקציונליות דינאמית לאתרי אינטרנט. נושא זה מלמד את כל הכלים והנושאים הנדרשים על מנת להבין ולכתוב בשפת  JavaScript.
+
Web forms — Working with user data
+
Web forms are a potent tool for interacting with users — most commonly, they are used for collecting data from users, or allowing them to control a user interface. In the articles listed below, we'll cover all the essential aspects of structuring, styling, and interacting with web forms.
+
נגישות אתרים
+
נגישות אתרים זה מושג המאגד בתוכו מספר פרקטיקות מקובלות אשר מטרתן היא להפוך את התוכן ברשת לנגיש עבור כמה שיותר אנשים, ללא השפעה של מוגבלות פיזית, סוג המכשיר, מיקום וגורמים נוספים. נושא זה נוגע בכל מה שאתם צריכים לדעת בנושא.
+
Web Performance - הפיכת האתר למהיר ורספונסיבי
+
ביצועים זו האמנות של הפיכת אתרי אינטרנט ויישומים מבוססי web למהירים ורספונסיביים לאינטראקציות של המשתמש, ללא השפעה של מהירות הגלישה של המשתמש, גודל המסך, הגבלות מכשיר וכד׳. 
+
כלים ובדיקות
+
נושא זה מכסה את כל הכלים שמפתחים צריכים על מנת לבחון ולבדוק את הפיתוח שלהם. 
+
תכנות צד-שרת
+
גם אם אתם מתרכזים בפיתוח צד-לקוח, יהיה זה שימושי והכרחי מאוד עבורכם להבין מהם שרתים ומהו קוד של צד השרת וכיצד הם עובדים יחד. נושא זה מעניק הכרות כללית כיצד צד השרת עובד, ומדריכים מפורטים המראים כיצד לבנות יישום צד שרת באמצעות שתי פריימוורקים פופולרים - Django (Python) and Express (node.js). 
+
+ +

דוגמאות הקוד שלנו

+ +

כל דוגמאות הקוד שלנו זמינים כמובן גם ב-GitHub. אם תרצו להוריד עותק מרוכז שלהם למחשב, תוכלו להוריד קובץ ZIP מרוכז.

+ +

אם אתם מעדיפים להעתיק את המאגר בדרך יותר מורכבת אך מאפשרת לכם לקבל עדכונים אוטומטיים לדוגמאות הקוד, ראו ההסבר בשפה האנגלית פה

+ +

צרו עמנו קשר

+ +

אם תרצו ליצור עמנו קשר בכל נושא, הדרך הטובה ביותר היא ב-learning area discourse thread או בערוצי ה-IRC. היינו רוצים לשמוע האם לדעתכם חסר משהו באתר, או נושא לא מוסבר לעומק או לא ברור וכמובן אם מצאתם שגיאה. כמובן, הרגישו חופשי לפנות בכל שאלה או בעיה. 

+ +

אם אתם מעוניינים לעזור ולפתח את התוכן פה באתר שלנו שלנו, ראו את המאמר בנושא how you can help וצרו עמנו קשר. אנחנו יותר מנשמח לדבר אתכם בנושא בין אם אתם סטודנטים, מורים, מפתחים מנוסים או סתם בא לכם לעזור לשפר את חווית הלמידה של הגולשים באתר.

+ +

ראו גם

+ +
+
Mozilla developer newsletter
+
הניוזלטר שלנו למפתחי Web - מקור מידע מעולה לכל רמות הניסיון. 
+
Web demystified
+
סדרה מצויינת של סרטוני וידאו המסבירה את הבסיס של פיתוח Web, נועדה בעיקר לחסרי רקע. נוצרה על ידי  Jérémie Patonnier.
+
Codecademy
+
אתר אינטראקטיבי מעולה ללימוד שפות תכנות מהבסיס.
+
Code.org
+
אתר בסיסי לתכנות אשר נועד בעיקר לחסרי רקע/ילדים.
+
freeCodeCamp.org
+
אתר אינטראקטיבי מעולה ללימוד פיתוח Web.
+
Teaching activities
+
A series of teaching activities for teaching (and learning) created by the Mozilla Foundation, covering everything from basic web literacy and privacy to JavaScript and hacking Minecraft.
+
Edabit
+
Hundreds of free interactive coding challenges in various languages.
+
diff --git a/files/he/learn/javascript/asynchronous/concepts/index.html b/files/he/learn/javascript/asynchronous/concepts/index.html new file mode 100644 index 0000000000..273c184474 --- /dev/null +++ b/files/he/learn/javascript/asynchronous/concepts/index.html @@ -0,0 +1,203 @@ +--- +title: עקרונות תכנות א-סינכרוני כלליים +slug: Learn/JavaScript/Asynchronous/Concepts +translation_of: Learn/JavaScript/Asynchronous/Concepts +--- +
{{LearnSidebar}}{{NextMenu("Learn/JavaScript/Asynchronous/Introducing", "Learn/JavaScript/Asynchronous")}}
+ +

+ במאמר זה אנחנו נעבור על מספר עקרונות חשובים בנושא תכנות א-סינכרוני וכיצד זה נראה בדפדפנים וב-JavaScript. חשוב להבין עקרונות אלו לפני שממשיכים למאמרים הבאים במודול זה. +

+ + + + + + + + + + + + +
ידע מוקדם:Basic computer literacy, a reasonable understanding of JavaScript fundamentals.
מטרה: + הבנה של העקרונות הבסיסיים מאחורי תכנות א-סינכרוני וכיצד אלו באים לידי ביטוי בדפדפנים וב-JavaScript.
+ +

Asynchronous - א-סינכרוני?

+ +

+ באופן נורמלי, קוד של תוכנית רץ בצורה עצמאית, כאשר רק דבר אחד קורה בכל רגע נתון. אם פונקציה מסויימת נשנעת על התוצאה של פונקציה אחרת, היא חייבית לחכות לפונקציה האחרת לסיים ולהחזיר את התוצאה ועד שזה לא קורה, כל התוכנית עוצרת מנקודת מבטו של המשתמש.

+ +

Mac אלו המשתמשים ב-, לדוגמא, + לפעמים רואים עיגול צבעוני... עיגול זה בעצם אומר למשתמש ״התוכנית הנוכחית שאתה מתמש בה הייתה צריכה לעצור ולחכות שמשהו הסתיים, וזה לוקח זמן..״

+ +

multi-colored macos beachball busy spinner

+ +

+ זו חווית שימוש מעצבנת, ולא ממש שימוש יעיל ביכולות המחשב, במיוחד בעידן שלמחשבים יש מספר ליבות מעבד זמינות. אין שום סיבה שאנחנו נחכה למשהו כשאנחנו יכולים להמשיך במקביל בעבודה שלנו בזמן שהמחשב עובד על אותה פעולה ויעדכן אותנו כשהפעולה הסתיימה. זה מאפשר לנו לבצע פעולות אחרות במקביל, וזה בעיקרון הבסיס של תכנות א-סינכרוני - asynchronous programming. זה תלוי בסביבת הפיתוח שבה אנחנו משתמשים (דפדני אינטרנט במקרה שלנו) להעניק למפתח APIs שיאפשרו לנו להריץ משימות באופן א-סינכרוני + + +

+ +

Blocking code

+ +

+ טכניקות א-סינכרוניות הן שימושיות מאוד, במיוחד בפיתוח web. כאשר יישום web רץ בדפדפן ומריץ שורות קוד מבלי להחזיר את השליטה לדפדפן, הדפדפן יכול להיראות כאילו הוא ״קפא״. זה נקרא blocking. הדפדפן חסום מלהמשיך ולטפל בפעולות מצד המשתמש ולבצע פעולות נוספות עד אשר יישום ה-web מחזיר את השליטה למעבד.

+ +

+ נסתכל על מספר דוגמאות על מנת להסביר למה אנחנו מתכוונים ב- blocking + +

+ +

ב simple-sync.html דוגמא שלנו (או כ דף אינטרנט), + + הוספנו מאזין אירוע מסוג click לכפתור כך שבכל פעם שהכפתור יילחץ, הוא יריץ פעולה שלוקחת המון זמן (מחשבת 10 מיליון תאריכים ואז מחזירה את האחרון לקונסולה) ולאחר מכן מוסיפה פסקה ל-DOM:

+ +
const btn = document.querySelector('button');
+btn.addEventListener('click', () => {
+  let myDate;
+  for(let i = 0; i < 10000000; i++) {
+    let date = new Date();
+    myDate = date
+  }
+
+  console.log(myDate);
+
+  let pElem = document.createElement('p');
+  pElem.textContent = 'This is a newly-added paragraph.';
+  document.body.appendChild(pElem);
+});
+ +

+ כשאתם מריצים את הדוגמא למלעלה, פתחו את הקונסולה ואז לחצו על הכפתור - אתם תשימו לב שהפסקה אינה מופיעה עד אשר חישוב התאיריכים הסתיים והוצגה ההודעה לקונסולה. הקוד רץ בסדר שבה הוא מופיע בקוד המקור והפעולה האחרונה לא תרוץ עד אשר הפעולה הקודמת לא סיימה.

+ +
+

לתשומת לב: הדוגמא הקודמת דיי לא מציאותית. אנחנו לעול לא נחשב 10 מיליון תאריכים בתוכנית אמיתית. דוגמא זו נועדה לתת לכם רק את ההבנה של תכנות א-סינכרוני.

+
+ +

בדוגמא השנייה שלנו, simple-sync-ui-blocking.html (ראו כדף אינטרנט), + אנחנו מנסים לדמות משהו קצת יותר ריאלי שאתם אולי תיתקלו בו בדף אמיתי. אנחנו חוסמים את האינטראקציה של המשתמש עם העיבוד של ממשק המשתמש. בדוגמא זו יש לנו שני כפתורים:

+ + + +
function expensiveOperation() {
+  for(let i = 0; i < 1000000; i++) {
+    ctx.fillStyle = 'rgba(0,0,255, 0.2)';
+    ctx.beginPath();
+    ctx.arc(random(0, canvas.width), random(0, canvas.height), 10, degToRad(0), degToRad(360), false);
+    ctx.fill()
+  }
+}
+
+fillBtn.addEventListener('click', expensiveOperation);
+
+alertBtn.addEventListener('click', () =>
+  alert('You clicked me!')
+);
+ +

+ אם תלחצו עלהכפתור הראשון ואז ישר לאחר מכן על השני אתם תראו שההודעה למשתמש לא מופיע עד אשר העיגולים לא סיימו להיות מעובדים. הפעולה הראשונה חוסמת את ביצוע הפעולה השנייה עד אשר הפעולה הראשונה תסתיים.

+ +
+

לתשומת לב: + זהו אמנם נראה לא טוב, אך זוהי רק דוגמא למה שמפתחים נתקלים בה ביישומים אמיתיים.

+
+ +

+ מדוע זה קורה? התשובה נעוצה בכך ש-JavaScript היא single threaded. בנקודה, אנחנו נרצה להציג בפניכם את הרעיון של threads.

+ +

Threads

+ +

Thread הוא בעיקרון תהליך יחיד שתוכנית יכולה להשתמש בה על מנת להשלים משימות. כל תהליך כזה יכול לבצע משימה אחת בכל פעם:

+ +
Task A --> Task B --> Task C
+ +

+ כל משימה תרוץ באופן טורי, רציף, אך לא סימולטני. משימה צריכה להסתיים כדי שהבאה בתור תחל בריצה.

+ +

+ כפי שאמרנו מקודם, הרבה מחשבים הם בעלי מספר רב של ליבות, כך שהם יכולים לבצע מספר דברים בבת אחת. שפות תכנות שתומכות בליבות מרובות יכולות להתשמש בליבות אלו על מנת לבצע מספר פעולות באופן סימולטני ובמקביל:

+ +
Thread 1: Task A --> Task B
+Thread 2: Task C --> Task D
+ +

JavaScript - single threaded

+ +

JavaScript היא single-threaded. + אפילו אם יש מספר ליבות, אנחנו יכולים רק להריץ משימה על thread יחיד, שנקרא main thread. הדוגמא שלנו מלמעלה מורצת כך:

+ +
Main thread: Render circles to canvas --> Display alert()
+ +

+ לאחר זמן מסויים, JavaScript קיבלה מס׳ כלים על מנת להתמודד עם בעיות אלו. + + Web workers + מאפשר לנו לשלוח חלק מהביצוע של JavaScript ל-thread נפרד שנקרא בשם worker, כך שאנחנו יכולים להריץ קודי JavaScript באופן סימולטני מקביל. בדרך כלל אנחנו נשתמש ב-worker להריץ תהליכי + + allow you to send some of the JavaScript processing off to a separate thread, called a worker, so that you can run multiple JavaScript chunks simultaneously. You'd generally use a worker to run expensive processes off the main thread so that user interaction is not blocked.

+ +
  Main thread: Task A --> Task C
+Worker thread: Expensive task B
+ +

+ כעת, לאחר שאנחנו יודעים זאת, נסתכל על simple-sync-worker.html או כדף אינטרנט, ונפתח את הקונסולה. + בקובץ זה כתבנו מחדש את הדוגמא שלנו לחישוב 10 מיליון תאריכים בworker thread נפרד. כעת כשאנחנו לוחצים על הכפתור, הדפדן מסוכל להציג את הפסקה לפני שחישוב התאיריכים הסתיימו. הפעולה הראשונה כבר לא חוסמת את הפעולה השנייה. + +

+ +

Asynchronous code קוד א-סינכרוני

+ +

Web workers הם מאוד שימושיים, אבל יש להם הגבלות. + אחת מהן היא שהם לא יכולים לגשת ל-{{Glossary("DOM")}} - אנחנו לא יכולים לגרום ל-worker לעשות שום דבר שיכול לעדכן את ממשק המשתמש, את ה-UI. אנחנו לא נוכל לעבד מיליון כדורים כחולים בתוך ה-worker שלנו. הוא בעיקרון יכול רק לעשות מניפולציות מספריות. +

+ +

+ הבעיה השנייה היא שלמרות שהקוד שרץ בתוך ה-000000 לא חוסם, הוא עדיין בסופו של דבר סינכרוני. זה הופך לבעיה כשאר פונקציה מתבססת על התוצאה של חישובים של תהליכים שקדמו לפונקציה. הסתכלו על התרשים הבא:

+ +
Main thread: Task A --> Task B
+ +

+ במקרה זה, משימה A עושה משהו כמו הבאת תמונה מהשרת, ואז משימה B עושה משהו עם התמונה הזו, כגון החלת פילטר. אם אנחנו נתחיל את משימה A ואז ישר נריץ את משימה B , אנחנו נקבל שגיאה כי התמנוה עדיין לא זמינה, כי משימה A לא הסתיימה עדיין.

+ +
  Main thread: Task A --> Task B --> |Task D|
+Worker thread: Task C -----------> |      |
+ +

+ במקרה הזה לדוגמא, יש לנו את משימה D שמבצעת שימוש בתוצאות של משימה B ומשימה C. אם אנחנו יכולים להבטיח שהתוצאות של שתי משימות אלו יהיהו זמינות בואתו הזמן, אז זה יכול להיות תקין, אבל זה בדרך כלל לא קורה. אם משימה D תנסה לרוץ לפני שהערכים שהיא צריכה לקבל זמינים עבורה, זה יחזיר לנו רוב הסיכויים שגיאה.

+ +

+ על מנת לתקן בעיות שכאלו, דפדנים מאפשרים לנו להריץ מס׳ פעולות באופן א-סינכרוני. תכונות כמו Promises מאפשרות לנו לקבוע משימה שתרוץ, כמו לדוגמא הבאת תמונה מהשרת, ולחכות עד אשר התוצאה של אותה משימה תוחזר שנריץ פעולה מסויימת אחרת.

+ +
Main thread: Task A                   Task B
+    Promise:      |__async operation__|
+ +

+ מאחר שהפעולה מתרחשת במקום אחר, ה-main thread לא חסום בזמן שהפעולה הא-סינכרונית מתרחשת. + +

+ +

+ אנחנו נסתכל כיצד אנחנו יכולים לרשום קוד א-סינכרוני במאמר הבא. +

+ +

לסיכום

+ +

+ עיצוב תוכנה מודרני סובב יותר ויותר סביב שימוש בתכנות א-סינכרוני, כדי לאפשר לתוכניות לעשות יותר מדבר אחד בכל פעם. כאשר נשתמש ב-API חדשים ובעלי יכולות מתקדמות, אנחנו נמצא יותר מקרים שבהם הדרך היחידה לבצע משהו מסויים היא רק באופן א-סינכרוני. זה היה דיי קשה בעבר לכתוב קוד א-סינכרוני. אמנם עדיין לוקח זמן להתרגל לכך, אבל זה נעשה הרבה יותר קל. ביתר המאמרים במודול זה אנחנו נסביר מדוע קוד א-סינכרוני הוא רלוונטי וחשוב וכיצד נעצב את הקוד על מנת להימנע מחלק מהבעיות שסקרנו במאמר זה. + + + יותר מדבר אחד בכל פעם. כשאתה משתמש בממשקי API חדשים וחזקים יותר, תמצא מקרים נוספים שבהם הדרך היחידה לעשות דברים היא בצורה אסינכרונית. פעם היה קשה לכתוב קוד אסינכרוני. זה עדיין לוקח להתרגל, אבל זה נעשה הרבה יותר קל. בשאר מודול זה נבדוק יותר מדוע חשוב קוד אסינכרוני וכיצד לתכנן קוד שנמנע מכמה מהבעיות שתוארו לעיל.

+ +

במודול זה

+ + diff --git a/files/he/learn/javascript/asynchronous/index.html b/files/he/learn/javascript/asynchronous/index.html new file mode 100644 index 0000000000..01ec7babb7 --- /dev/null +++ b/files/he/learn/javascript/asynchronous/index.html @@ -0,0 +1,43 @@ +--- +title: Asynchronous JavaScript +slug: Learn/JavaScript/Asynchronous +translation_of: Learn/JavaScript/Asynchronous +--- +
{{LearnSidebar}}
+ +

במודות זה אנחנו נסתכל על {{Glossary("asynchronous")}} {{Glossary("JavaScript")}}, ומדוע זה חשוב, וכיצד אנחנו יכולים להשתמש בזה על מנת לטפל בפעולות חוסמות () כמו הבאת משאבים מהשרת.

+ +

Prerequisites

+ +

Asynchronous JavaScript הוא יחסית נושא מתקדם ואנו ממליצים לכם לעבור על המודולים צעדים ראשונים ב-JavaScript ועל אבני הבניין של JavaScript לפני שתתחילו ללמוד מודול זה.

+ +

אם אינכם בקיאים בקונספט של תכנות א-סינכרוני, אנא התחילו עם המאמר עקרונות תכנות א-סינכרוני במודול זה. אם אתם כן בקיאים, אתם ככל הנראה יכולים להתחיל ב-הצגת Asynchronous JavaScript.

+ +
+

הערה: אם אתם עובדים על מחשב\טבלט\מכשיר אחר שאין לכם אפשרות ליצור עליו קבצים אישיים, אתם יכולים לנסות את (רוב) דוגמאות הקוד על תוכנות קוד אינטרנטיות כמו JSBin או Thimble.

+
+ +

מדריכים

+ +
+
עקרונות תכנות א-סינכרוני כלליים 
+
+

במאמר זה אנחנו נעבור על מספר עקרונות חשובים בנושא תכנות א-סינכרוני וכיצד עקרונות אלו באים לידי ביטוי בדפדפנים וב-JavaScript. אתם אמורים להבין עקרונות אלו בטרם תמשיכו למאמרים נוספים במודול זה.

+
+
הצגת Asynchronous JavaScript
+
במאמר זה נסקור בקצרה את הבעיות הקשורות ל-JavaScript סינכרונית, ונסתכל לראשונה על האופציות השונות ב-JavaScript א-סינכרוני שניתקל בהן, ונראה כיצד טכניקות אלו יכולות לפתור לנו בעיות.
+
Asynchronous JavaScript: שימוש ב-Intervals ו-Timeouts
+
במאמר זה נסתכל על המתודות המסורתיות שקיימות ב-JavaScript להרצת קוד בצורה א-סינכרונית לאחר שזמן מסויים עבר או בקבועי זמן מסויימים ונדון במקרים שהם רלוונטיים לשימוש וכן נדון בסוגיות הטבועות בהם.
+
טיפול בפעולות א-סינכרוניות באמצעות Promises
+
Promises הם בעיקרון תכונה חדשה יחסית של שפת JavaScript המאפשרת לך לדחות פעולות נוספות עד      לאחר השלמת הפעולה הקודמת, או להגיב לכישלונה. זה מאוד שימושי להגדרת רצף של פעולות שיעבדו בצורה מסויימת. מאמר זה מראה לך כיצד promises עובדות, היכן תראה אותן בשימוש ב- WebAPIs,      ואיך לכתוב promises משלך.
+
הפיכת Asynchronous Programming לקל יותר עם async ועם await
+
Promises יכולות להיות קצת מורכבות לביצוע והבנה, ודפדפנים מודרניים הטמיעו את הפונקציות async ואת האופרטור await - הראשון מאפשר לפונקציות סטנדרטיות להתנהג בצורה עקיפה כא-סינכרוניות עם Promises ואילו בשני אנחנו יכולים לעשות שימוש בתוך פונקציות async על מנת לחכות ל-promises לפני שהפונקציה ממשיכה, כך שנוכל לקשור promises בצורה קלה יותר. מאמר זה מסביר את async/await.
+
בחירת האפשרות המתאימה
+
בסיום המודול אנחנו נדון בהבדלים שבין הטכניקות השונות שנגענו בהם, ונדון באיזו טכניקה יהיה מומלץ להשתמש במקרים השונים.
+
+ +

ראו גם

+ + diff --git a/files/he/learn/javascript/asynchronous/introducing/index.html b/files/he/learn/javascript/asynchronous/introducing/index.html new file mode 100644 index 0000000000..3f5a342e1e --- /dev/null +++ b/files/he/learn/javascript/asynchronous/introducing/index.html @@ -0,0 +1,281 @@ +--- +title: הצגת asynchronous JavaScript +slug: Learn/JavaScript/Asynchronous/Introducing +translation_of: Learn/JavaScript/Asynchronous/Introducing +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Concepts", "Learn/JavaScript/Asynchronous/Timeouts_and_intervals", "Learn/JavaScript/Asynchronous")}}
+ +

במאמר זה אנחנו נסקור שוב את הבעיות הקשורות ב-Synchronous JavaScript, ונסתכל לראשונה על הטכניקות לא-סינכרוניות שניתקל בהן, וכיצד הן יכולות לסייע לנו לפתור בעיות אלו.

+ + + + + + + + + + + + +
ידע מוקדם:Basic computer literacy, a reasonable understanding of JavaScript fundamentals.
מטרה:להבין מהי שAsynchronous JavaScript וכיצד היא שונה מ-Synchronous JavaScript, ומתי להשתמש בה.
+ +

Synchronous JavaScript

+ +

על מנת שנוכל להבין מה זה {{Glossary("asynchronous")}} JavaScript אנחנו צריכים תחילה להבין מה זה {{Glossary("synchronous")}} JavaScript. חלק זה של המאמר יסקור שוב חלק מהמידע שכבר עברנו עליו במאמר הקודם.

+ +

הרבה מהפונקציונליות שראינו במודולים הקודמים של מדריך זה היו דיי סינכרוניים - אנחנו מריצים קוד מסויים והתוצאה של אותה ריצה מוחזרת כאשר הדפדפן יכול להחזיר את התוצאה. נסתכל כעת על דוגמא פשוטה ב-דף זהאו בקוד המקור:

+ +
const btn = document.querySelector('button');
+btn.addEventListener('click', () => {
+  alert('You clicked me!');
+
+  let pElem = document.createElement('p');
+  pElem.textContent = 'This is a newly-added paragraph.';
+  document.body.appendChild(pElem);
+});
+
+ +

בקוד זה, השורות מורצות אחת אחרי השנייה:

+ +
    +
  1. אנחנו יוצרים הפנייה לאלמנט {{htmlelement("button")}} שכבר זמין ב-DOM.
  2. +
  3. אנחנו מוסיפים מטפל אירוע בשם click כך שכאשר הכפתור נלחץ: +
      +
    1. הודעת ()alert מוצגת למשתמש.
    2. +
    3. ברגע שהודעה זו נסגרת, אנחנו יוצרים אלמנט {{htmlelement("p")}}.
    4. +
    5. לאחר מכן אנחנו מכניסים לתוך האלמנט  {{htmlelement("p")}} תוכן.
    6. +
    7. בסוף אנחנו משייכים את ה- {{htmlelement("p")}} ל-body.
    8. +
    +
  4. +
+ +

בעוד שכל תהליך שכזה נמצא בהרצה או עיבוד, שום דבר אחר לא יכול להתרחש - יתר העיבוד מושהה. זה מכיוון שכפי שראינו במאמר הקודם ש-JavaScript היא single threaded. רק דבר אחד יכול להתרחש בכל פעם על ה-single main thread, וכל היתר חסום לביצוע או לעיבוד עד אשר אותה פעולה תושלם.

+ +

בדוגמא למעלה, אחרי שלחצנו על הכפתור, הפסקה לא הופיעה עד לאחר שכפתור ה-OK לא נלחץ בחלונית הקופצת. אתם יכולים לנסות זאת בעצמכם:

+ + + +

{{EmbedLiveSample('Synchronous_JavaScript', '100%', '70px')}}

+ +
+

לתשומת לב: חשוב לזכור שאמנם ()alert מאוד שימושי לשם הסבר על פעולות סינכרוניות שחוסמות את המשך הפעילות, זוהי פונקציה שאינה בשימוש רב ביישומים אמיתיים מטעמים של חווית משתמש לרוב.

+
+ +

Asynchronous JavaScript

+ +

לאור הסיבות שנסקרו למעלה, הרבה Web API משתמשים בקוד א-סינכרוני על מנת לפעול, במיוחד אלו שניגשים או מביאים משאב מסויים מגורם חיצוני, כמו הבאה של קובץ מהרשת, גישה למאגר מידע והחזרת מידע מתוכו, הפעלת של הזרמת וידאו באמצעות מצלמת רשת וכד׳.

+ +

מדוע העבודה עם קוד א-סינכרוני היא מורכבת? נסתכל על דוגמא זריזה. כאשר אנחנו מבקשים תמונה משרת מסויים, איננו יכולים לקבל את התשובה באופן מיידי. זה אומר שהפסאודו-קוד הרשום להלן לא יעבוד:

+ +
var response = fetch('myImage.png');
+var blob = response.blob();
+// display your image blob in the UI somehow
+ +

זה מכיוון שאנחנו לא יודעים כמה זמן ייקח לתמונה להגיע מהשרת, אז כאשר אנחנו נרצה להריץ את שורת הקוד הבאה, היא תחזיר לנו שגיאה (אולי לסירוגין, אולי בכל פעם) מכיוון שה-response אינו זמין עבורנו עדיין. במקום זאת, אנחנו צריכים שהקוד שלנו יחכה ל-response שיוחזר אלינו לפני שאנחנו מנסים לעשות עם response פעולה כלשהי.

+ +

יש שני סוגים עיקריים של קוד א-סינכרוני שאנחנו ניתקל בהם בקוד javascript, יש את ה-callbacks הותיקים ואת ה-promises החדשים יותר.  במאמר זה נסקור את שניהם.

+ +

Async callbacks

+ +

Async callbacks אלו פונקציות המועברות כפרמטר (ארגומנט) לפונקציה אחרת, כאשר אנחנו קוראים לפונקציה אחרת אשר מריצה קוד ברקע. כאשר הקוד שברקע סיים לרוץ, הוא קורא לאותן פונקציות callbacks על מנת לציין שהפעולה שהייתה ברקע הסתיימה או לציין שמשהו הסתיים.

+ +

שימוש ב-callbacks יחסית נחשב מיושן כעת, אבל אנחנו עדיין נראה שימוש רב שלהם ב-APIs ישנים אבל עדיין מאוד שימושיים.

+ +

דוגמא ל-async callback אפשר לראות בפרמטר השני של {{domxref("EventTarget.addEventListener", "addEventListener()")}} (כפי שראינו בפעולה למעלה):

+ +
btn.addEventListener('click', () => {
+  alert('You clicked me!');
+
+  let pElem = document.createElement('p');
+  pElem.textContent = 'This is a newly-added paragraph.';
+  document.body.appendChild(pElem);
+});
+ +

הפרמטר הראשון הוא הסוג של האירוע שאנחנו רוצים להאזין להתרחשות שלו, והפרמטר השני הוא פונקציית callback שמופעלת ברגע שהאירוע מתרחש.

+ +

כאשר אנחנו מעבירים callback function כפרמטר לפונקציה אחרת, אנחנו רק מעבירים את הגדרת הפונקציה כפרמטר, כלומר ה-callback function לא מופעל באופן מיידי. הוא נקרא לאחר מכן (“called back”) באופן א-סינכרוני איפשהו בתוך הגוף של הפונקציה שקיבלה אותו כפרמטר. הפונקציה שקיבלה אותו כפרמטר היא האחראית להפעיל את ה-callback function כשנצטרך.

+ +

אנחנו יכולים לכתוב פונקציות משלנו שיכילו callback function באופן דיי פשוט יחסית. נסתכל על דוגמא שמעלה משאב באמצעות XMLHttpRequest API (דף האינטרנט, ו- קוד המקור):

+ +
function loadAsset(url, type, callback) {
+  let xhr = new XMLHttpRequest();
+  xhr.open('GET', url);
+  xhr.responseType = type;
+
+  xhr.onload = function() {
+    callback(xhr.response);
+  };
+
+  xhr.send();
+}
+
+function displayImage(blob) {
+  let objectURL = URL.createObjectURL(blob);
+
+  let image = document.createElement('img');
+  image.src = objectURL;
+  document.body.appendChild(image);
+}
+
+loadAsset('coffee.jpg', 'blob', displayImage);
+ +

כאן יצרנו את פונקציית ()displayImage שפשוט מקבלת blob שמועבר אליה ויוצרת לו URL באמצעות URL.createObjectURL(blob). לאחר מכן הפונקציה יוצרת אלמנט HTML מסוג img, משימה לו את הערך של ה-src לאותו URL שנוצר לנו ומשייכת את ה-image ל-body. 

+ +

בנוסף, יצרנו פונקציה בשם ()loadAsset שמקבלת כפרמטרים כתובת URL, סוג הקובץ וכן פונקציית callback (שימו לב שהשם שנתנו לפרמטר - callback - הוא לשם הנוחות בלבד וניתן לקרוא לפרמטר זה בכל שם). פונקציית ()displayImage משתמשת ב-XMLHttpRequest (לרוב משתמשים בקיצור שלו - "XHR") על מנת להביא משאב מ-URL מסויים לפני שמעבירים את התגובה של אותה XMLHttpRequest לפונקציית callback שלנו - לפונקציית  ()displayImage.

+ +

במקרה הזה, פונקציית ה-callback שלנו מחכה ש-XHR יסיים להוריד את המשאב שהוא הביא (באמצעות שימוש במטפל אירוע מסוג onload), וזאת לפני שהיא תקבל את המשאב.

+ +

Callbacks הם מאוד ורסטיליים - לא רק שהם מאפשרים לנו לשלוט בסדר שבו פונקציות ירוצו ואיזה מידע יועבר ביניהן, הן גם מאפשרות לנו להעביר מידע לפונקציות שונות בהתאם לנסיבות. כך שאנחנו יכולים להריץ פעולות שונות על המשאב שהתקבל או התגובה שהתקבלה כמו processJSON(), displayText(), וכד׳. 

+ +

שימו לב שלא כל ה-Callbacks הם א-סינכרוניים וחלקם הם סינכרוניים. כך לדוגמא, כאשר אנחנו משתמשים ב- {{jsxref("Array.prototype.forEach()")}} על מנת לעבור באמצעות לולאה על איברים במערך (ראו כדף אינטרנט, וכן את קוד המקור):

+ +
const gods = ['Apollo', 'Artemis', 'Ares', 'Zeus'];
+
+gods.forEach(function (eachName, index){
+  console.log(index + '. ' + eachName);
+});
+ +

בדוגמא זו, אנחנו עוברים על מערך של Greek gods ומדפיסים את מספרי האינדקס והערכים לקונסולה. הפרמטר שאנחנו נותנים ל-()forEach הוא פונקציית callback, אשר בעצמו מקבל שני פרמטרים, שם הפריט במערך ומספר האינדקס. יחד עם זאת, היא  לא מחכה לשום דבר, היא פשוט רצה באופן אוטומטי. 

+ +

Promises

+ +

Promises אלו בעצם הסגנון החדש לקוד א-סינכרוני שאנחנו נראה שמבוצע בהם שימוש ב-Web APIs מודרניים. דוגמא טובה לכך היא fetch() API, אשר הוא בעצם כמו גרסה מודרנית ויעילה יותר של {{domxref("XMLHttpRequest")}}. נסתכל על דוגמא מהמאמר שלנו בנושא הבאת מידע מהשרת אשר תגיעו אליו בהמשך:

+ +
fetch('products.json').then(function(response) {
+  return response.json();
+}).then(function(json) {
+  products = json;
+  initialize();
+}).catch(function(err) {
+  console.log('Fetch problem: ' + err.message);
+});
+ +
+

לתשומת לב: אתם יכולים למצוא את הגרסה הסופית ב- GitHub (ראו כאן את קוד המקור, וגם כדף אינטרנט).

+
+ +

כאן אנחנו רואים ש-fetch() לוקח פרמטר אחד - את ה-URL של המשאב שנאחנו רוצים להביא מהרשת - והוא מחזיר promise. ה-promise היא בעצם אובייקט המייצג השלמה או כישלון של פעולת ה-שaysync. בצורה מסויימת, זו הדרך של הדפדפן להגיד ״אני מבטיח לחזור אליך עם תשובה ברגע שאוכל״. מכאן השם promise.

+ +

צריך להתרגל לרעיון הזה על ידי תרגול. זה מרגיש קצת מוזר בהתחלה, כמו החתול של שרדינגר - {{interwiki("wikipedia", "Schrödinger's cat")}}. אף אחת מהאפשרויות לא קרתה עדיין, אז פעולת ההבאה - פעולת ה-fetch, כרגע מחכה לתוצאה של פעולת הדפדפן - להשלמה שלה בעתיד. לאחר מכן שיש לנו שלושה קודי בלוק שמשורשרים לסוף fetch():

+ + + +
+

לתשומת לב: אתם תלמדו עוד הרבה על promises בהמשך המודול הזה, אז אל דאגה אם לא הבנתם אותם עד הסוף. זוהי רק סקירה.

+
+ +

The event queue

+ +

פעולות א-סינכרוניות כמו promises מושמות לתוך ה-event queue, אשר רץ לאחר שה-main thread סיים את העיבודים שלו, כך שהם לא יחסמו קוד JavaScript שבא אחריהם. הפעולות שב-promises יושלמו ברגע שיתאפשר, ויחזירו את התוצאה שלהן לסביבת הjavascript. Async operations like promises are put into an event queue, which runs after the main thread has finished processing so that they do not block subsequent JavaScript code from running. The queued operations will complete as soon as possible then return their results to the JavaScript environment.

+ +

Promises מול callbacks

+ +

ל-Promises יש קצת דמיון ל-callbacks הוותיקים. הם בעיקרון אבוייקט שהוחזר, אליו אנחנו מחברים פונקציות callbacks, ולא צריכים להעביר callbacks לתוך פונקציה.

+ +

יחד עם זאת, promises נוצרו במיוחד עבור טיפול בפעולת א-סינכרוניות, ויש להם הרבה יתרונות על ה-callbacks הוותיקים:

+ + + +

ההתנהגות של קוד א-סינכרוני

+ +

בואו נעמיק בדוגמא שתסביר לנו יותר לעומק את ההתהנגות של קוד א-סינכרוני, שמראה מה יכול לקראת כשאנחנו לא בקיאים לגמי בסדר של הרצת הקוד וההבעיות שיש בניסיון לטפל בקוד א-סינכרוני כמו בקוד סינכרוני. הודמא הבא היא יחסית דומה למה שראינו בעבר. sכדף אינטרנט, וגם קוד המקור). הבדל אחד הוא שכללנו מספר ביטויים של {{domxref("console.log()")}} על ממנת להמחיש את הסדר שאנחנו נחשוב שבו הקוד ירוץ

+ +
console.log ('Starting');
+let image;
+
+fetch('coffee.jpg').then((response) => {
+  console.log('It worked :)')
+  return response.blob();
+}).then((myBlob) => {
+  let objectURL = URL.createObjectURL(myBlob);
+  image = document.createElement('img');
+  image.src = objectURL;
+  document.body.appendChild(image);
+}).catch((error) => {
+  console.log('There has been a problem with your fetch operation: ' + error.message);
+});
+
+console.log ('All done!');
+ +

הדפדפן יתחיל להריץ את הקוד, הוא יראה את ה-console.log() הראשון ויריץ אותו. ולאחר מכן ייצור את המשתנה image .

+ +

הוא לאחר מכן ימשיך לשורה הבאה, ויתחיל להריץ את הבלוק קוד של fetch(), אבל מכיוון ש-fetch() מורץ באופן א-סינכרוני בלי חסימה, הדפדפן ימשיך לקוד שלאחר הקוד של ה-promise-related code, ולכן יגיע ל-console.log() האחרון ( All done!) ואותו יציג לקונסולה. ימשיך לרוץ

+ +

רק ברגע שהבלוק של ה-code>fetch() סיים לחלוטין לרוץ והביא תוצאה - result באמצעות הבלוקים של .then(), אנחנו נראה לבסוף את הההודעה שב-console.log() השני (It worked ;)). כך שההודעות הופיעו בסדר שונה ממה שאולי חשבתם:

+ + + +

אם זה מבלבל אתכם, הסתכלו על הדוגמא הבאה:

+ +
console.log("registering click handler");
+
+button.addEventListener('click', () => {
+  console.log("get click");
+});
+
+console.log("all done");
+ +

זה מאוד דומה בהתנהגות - ה-console.log() הראשון והשלישי יציגו את ההודעות שלהן מיד, אבל ה-console.log() השני יהיה חסום להצגה עד אשר מישהו ילחץ על הכפתור. הדוגמא הקודמת פועלת בדרך דוה, למעט כך שבמקרה שההודעה השנייה חסומה בשרשרת ההבטחות המביאות משאב מסויים ומוצגת רק כאשר שרשרת ההבטטחות הושלמה, ולא כאשר המשתמש ילחץ על כפתור. .

+ +

בדוגמה של קוד פחות טריוויאלי, קוד מהסוג של הדוגמא הראשונה עלולה לגרום לבעיה - אינכם יכולים לכלול בלוק קוד אסינכרוני המחזיר תוצאה, עליה אתם מסתמכים בהמשך בבלוק קוד סינכרוני. אינכם כולים להבטיח שפונקציית ה-שaysync תחזור לפני שהדפדפן יעבד את חסימת האסינכרון.

+ +

על מנת לראות זאת בפעולה, נסו לעשות עותק מקומי של To see this in action, try taking a local copy of הדוגמאו תשלנו, ושנו את ה- console.log() שלישית כך:

+ +
console.log ('All done! ' + image + 'displayed.');
+ +

אתם אמורים לקבל שגיאה בקונסולה במקום ההודעה השלישית :

+ +
TypeError: image is undefined; can't access its "src" property
+ +

זה מכיוון שבזמן שהדפדפן מנסה להריץ את ה-console.log() השלישית, הבלוק קוד של fetch() עדיין לא סיים לרות, כך שהמשתנה image לא ניתן לו ערך עדיין.

+ +

למידה עצמאית: פכו את הכל ל- async!

+ +

על מנת לתקן את ה- fetch(), ולהפוך את שלושת -console.log() להיות מופעים בסדר הרצוי, אתם יכולים לעשות את ה-console.log() השלישי שירוץ גם הוא בצורה א-סינכרוני. את זה ניתן לעשות באמצעות העברה שלו לתוך .then() אחר, אשר משורשר לתוך הסוף של ה-.then() השני, או באמצעות פשוט העברה שלו לתוך ה-.then() השני. נסו לתקן זאת.

+ +
+

לתשומת לב: אם נתקעתם, אתם יכולים למצוא את התשובה כאן או כ דף אינטרנט also). אתם גם יכולים למצוא עוד הרבה על promises במדריך שלנו בנושא טיפול בפעולות א-סינכרוניות באמצעות Promises, בהמשך המודול הזה.

+
+ +

לסיכום

+ +

במבנה הבסיסי שלה, JavaScript היא סינכרונית, שפה single-threaded,כך רק פעולה אחת יכולה להיות מעובדת בכל זמן נתון. יחד עם זאת, הדפדפנים הגדירו פונקציות ו-APIs שמאפשרים לנו לרשום פונקציות שלא ירוצו באופן סינכרוני, ובמקום זאת, יופעלו באופן א-סינכרוני כאשר אירוע מסויים מתרחש. זה אומר שאנחנו יכולים לתת לקוד שלנו לעשות דברים אחרים באותו הזמן, מבלי לחסום או לעצור את ה-main thread.

+ +

בין אם אנחנו רוצים להירץ קוד באופן סינכרוני או א-סינכרוני, זה תלוי במה שאנחנו מנסים לעשות.

+ +

יש פעמים שאנחנו נרצה שדברים יועלו ויתרחשו במיידי. לדוגמא, כאשר המתשמש מגדיר סגנון לאתר ואתם רוצים שהסגנון יוחל באופן מיידי.

+ +

אם אנחנו מריצים פעולה מסויימת שלוקח לה זמן, כמו לדוגמא גישה למאגר מידע ושימוש בתוצאות על מנת ליצור תבניות לדגומא, זה יהיה עדיף להעביר את הפעולה הזו מחוץ ל-main thread, כך שתתצבע באופן א-סינכרוני. עם הזמן, אתם תלמדו מתי זה היה הגיוני לבחור בטכניקה א-סינכרונית ולא בסינכורנית.

+ + + +

{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Concepts", "Learn/JavaScript/Asynchronous/Timeouts_and_intervals", "Learn/JavaScript/Asynchronous")}}

+ +

במודול זה

+ + diff --git a/files/he/learn/javascript/asynchronous/promises/index.html b/files/he/learn/javascript/asynchronous/promises/index.html new file mode 100644 index 0000000000..87c8839084 --- /dev/null +++ b/files/he/learn/javascript/asynchronous/promises/index.html @@ -0,0 +1,589 @@ +--- +title: Graceful asynchronous programming with Promises +slug: Learn/JavaScript/Asynchronous/Promises +translation_of: Learn/JavaScript/Asynchronous/Promises +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Timeouts_and_intervals", "Learn/JavaScript/Asynchronous/Async_await", "Learn/JavaScript/Asynchronous")}}
+ +

Promises הן תכונה חדשה יחסית ב-JavaScript, אשר מאפשרת לנו לדחות פעולות מסוייומות עד אשר פעולותדמות להן יושלמו, או שיגיבו לכך שהן נכשלו. זוהי תכונה מאוד שימושית על מנת ליצור רצף של פעולות א-סינכרוניות שיעבדו בצור הטובה. מאמר זה נועד להסביר כיצד promises עובדות, כיצד אנו נראה אותם בשימוש ב-web APIs וכיצד נכתוב promises משלנו.

+ + + + + + + + + + + + +
ידע מוקדם:Basic computer literacy, a reasonable understanding of JavaScript fundamentals.
מטרה:להבין מהן promises וכיצד להשתמש בהן.
+ +

מהן promises?

+ +

סקרנו קצת Promises במאמר הראשון במודול זה, אבל במאמר זה נסקור אותן יותר לעומק.?

+ +

בעיקרון promise הוא בעצם אובייקט שמייצג מצב ביניים של פעולה - בפועל, promise היא מעין הבטחה שתוצאה מסויימת תוחזר בנקודה מסויימת בעתיד. אין שום הבטחה מתי הפעולה תושלם ומתי התוצאה תוחזר, אבל יש הבטחה שכאשר התוצאה מוכנה, או שכאשר הפעוללה נכשלה, הקוד שסיפקנו ירוץ על מנת לעשות משהו עם תוצאה מוצלחת או להתמודד עם כשלון בפעולה.

+ +

באופן כללי, אנחנו פחות מתעניינים בזמן שייקח לפעולה א-סינכרונית להחזיר את התוצאה שלה (אלא אם כן מדובר בזמן יותר מדי ארוך), ואנחנו יותר מעוניינים בכך שתהיה לנו אפשרות להגיב לאותה תגובה כאשר היא תחזור, לא משנה מהי התגובה. וכמובן, זה נחמד שאותה פעולה לא חוסמת את הקוד מלרוץ.

+ +

אחד מהשימושים של promise שאנחנו נראה הוא ב-web APIs שמחזירים promise. נניח ויש לנו יישום וידאו צ׳אט. ליישום זה יש חלון עם רשימת החברים של המשתמש, ובלחיצה על כפתור ליד שם החבר, תחל שיחת וידאו עם אותו חבר.

+ +

מטפל האירוע של הכפתור הזה קורא ל- {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} על מנת לקבל גישה למיקרופון ולמצלמה של המשתמש. מאחר ו-()getUserMedia חייב לוודא שלמשתמש יש אישור להשתמש באותם מכשירים ולבקש מהמשתמש לבחור איזה מיקרופון ואיזו מצלמה להשתמש בהם או בכל שילוב אחר. בזמן הבקשה הזו, פעולה זו יכולה לחסום את המשך התוכנית לא רק עד אשר כל האישורים האלו התקבלו, אלא גם עד אשר המצלמה והמיקרופון יתחברו. בנוסף, המשתמש אולי לא יגיב באופן מיידי לבקשות אלו. זה יכול לקחת הרבה זמן.

+ +

מאחר והקריאה ל- ()getUserMedia נעשית מה- browser's main thread, הדפדפן חסום עד אשר ()getUserMedia תסיים. ברור כמובן שזו לא אפשרות מקובלת בימים אלו. ללא promises, כל דבר בדפדפן היה נהפך ללא שימושי עד אשר המשתמש יחליט מה לעשות עם המצלמה והמיקרופון. אז במקום לחכות למשתמש, לקבל את המכשירים שנבחרו, ולהחזיר את ה-{{domxref("MediaStream")}} שנוצר למקורות אלו, ()getUserMedia מחזיר {{jsxref("promise")}} אשר נפתר עם {{domxref("MediaStream")}} ברגע שהוא זמין.

+ +

הקוד של יישום הוידאו צאט שלנו, עשוי להיראות כך?:?

+ +
function handleCallButton(evt) {
+  setStatusMessage("Calling...");
+  navigator.mediaDevices.getUserMedia({video: true, audio: true})
+    .then(chatStream => {
+      selfViewElem.srcObject = chatStream;
+      chatStream.getTracks().forEach(track => myPeerConnection.addTrack(track, chatStream));
+      setStatusMessage("Connected");
+    }).catch(err => {
+      setStatusMessage("Failed to connect");
+    });
+}
+
+ +

הפונקציה הזו מתחילה בכך שהיא משתמש בפונקציה שנקראת ()setStatusMessage על מנת לעדכן שורת עדכון למשתמש עם הטקסט: "Calling...", שמעידה על כך שמבוצע ניסיול החל בשיחה. לאחר מכן היא קוראת לפונקציה ()getUserMedia, ומבקשת שתחל בסטרים (stream) ?שיש לו גם וידאו וגם אודיו וברגע שהסטרים יהיה מוכן, היא ממשיכה בפעולות לשם הקמת הסטרים וחיבור המצלמה והאודיו. לאחר מכן היא מציגה למשתמש הודעה ״Connected״. 

+ +

אם ()getUserMedia תיכשל, בלוק הקוד של catch ירוץ. הוא משתמש שוב ב- ()setStatusMessage על מנת להציג למשתמש שהתרחשה שגיאה. 

+ +

הדבר החשוב כן הוא שהקריאה של ()getUserMedia מוחזרת כמעט באופן מיידי, גם אם הסטרים של המצלמה לא התקבל עדיין. אפילו אם הפונקציה של ()handleCallButton סיימה להריץ את הקוד שבתוכה והחזירה את השליטה לקוד שקרא לה, כאשר ()getUserMedia תסיים את הפעולה שלה, בין אם בהצלחה ובין אם תתרחש שגיאה, פונקציה זו תקרא שוב לאותו מטפל אירוע שסיפקנו לה. כלומר, היישום ימשיך לעבוד ולא יחכה לזרם הוידאו ולא ימנע מיתר הקוד להמשיך לרוץ. 

+ +
+

לתשומת לב:  לפרטים נוספים אודות נושא מורכב זה של וידאו ואודיו, ראו Signaling and video calling.

+
+ +

הבעיה עם callbacks

+ +

על מנת להבין לעומק מדוע promises הן דבר טוב, יעזור לנו לחשוב על ה-callbacks המיושנות ולהבין מדוע הן בעייתיות. 

+ +

ננסה להמחיש זאת באמצעות דוגמא להזמנת פיצה כאנלוגיה. יש מספר שלבים שאנחנו צריכים לעשות ולהשלים בהצלחה, אשר לא ממש הגיוני לבצע אותם בסדר אחר או לבצע אותם בסדר הנכון, אבל בלי לחכות שהשלב הקודם הסתיים:

+ +
    +
  1. בחירת התוספות לפיצה - זה יכול לקחת זמן אם אנחנו לא ממש בטוחים איזו תוספת אנחנו רוצים על הפיצה ושלב זה יכול להיכשל אם בסופו של דבר לא קיבלנו החלטה איזו תוספת אנחנו רוצים, או אם בסוף החלטנו לאכול משהו אחר. 
  2. +
  3. בהנחה והחלטנו על תוספת, לאחר מכן אנחנו מבצעים הזמנה של הפיצה שאנחנו רוצים. שלב זה יכול לקחת זמן עד אשר הפיצה תהיה מוכנה, ואף יכול להיכשל אם לפיצרייה אין את המרכיבים הנכונים. 
  4. +
  5. בשלב האחרון אנחנו אוספים את הפיצה ואוכלים, גם שלב זה יכול להיכשל אם לא שילמנו לדוגמא על הפיצה או לא באנו לאסוף את הפיצה. 
  6. +
+ +

עם ה-callbacks הישנות, קוד מופשט שלנו ייראה בערך כך: 

+ +
chooseToppings(function(toppings) {
+  placeOrder(toppings, function(order) {
+    collectOrder(order, function(pizza) {
+      eatPizza(pizza);
+    }, failureCallback);
+  }, failureCallback);
+}, failureCallback);
+ +

קוד זה הוא מבולגן וקשה להבנה, ולפעמים גם נקרא כ-callback hell, הוא גם דורש שהפונקציה ()failureCallback תיקרא כמה פעמים (בעבור כל פונקציה משורשרת) ויש לו גם חסרונות נוספים.

+ +

שדרוג עם  promises

+ +

Promises הופכות את סיטואציות כמו למעלה להרבה יותר פשוטות לכתיבה, פירוש וריצה. אם נציג את הקוד המופשט שלנו שוב באמצעות promises א-סינכרוניות, הוא ייראה כך:

+ +
chooseToppings()
+.then(function(toppings) {
+  return placeOrder(toppings);
+})
+.then(function(order) {
+  return collectOrder(order);
+})
+.then(function(pizza) {
+  eatPizza(pizza);
+})
+.catch(failureCallback);
+ +

זה כבר הרבה יותר טוב- הרבה יותר קל להבין מה קורה כאן והיינו צריכים רק בלוק קוד אחד של ()catch. בעבור כל השגיאות שאולי יתרחשו. כל הקוד הזה אינו חוסם את ה-main thread (כך שאנחנו יכולים להמשיך לראות טלווזיה עד אשר הפיצה תהיה מוכנה), וכל פעולה תחכה בוודאות עד אשר הפעולה הקודמת תסיים לפני שהיא תרוץ. אנחנו יכולים לקשור מספר פעולות א-סינכרוניות כך שיתרחשו אחת אחרי השנייה מכיוון שכל בלוק קוד של (.....)then. מחזיר promise חדשה, שנפתח כאשר הקוד שבתוך ה-(.....)then. הרלוונטי מסיים לרוץ. 

+ +

באמצעות שימוש בפונקציות חץ (arrow functions), אנחנו אפילו יכולים להפוך את הקוד לעוד יותר פשוט: 

+ + + +
chooseToppings()
+.then(toppings =>
+  placeOrder(toppings)
+)
+.then(order =>
+  collectOrder(order)
+)
+.then(pizza =>
+  eatPizza(pizza)
+)
+.catch(failureCallback);
+ +

או אפילו בצורה הזו:

+ +
chooseToppings()
+.then(toppings => placeOrder(toppings))
+.then(order => collectOrder(order))
+.then(pizza => eatPizza(pizza))
+.catch(failureCallback);
+ +

זה עובד מכיוון שעם פונקציות חץ, x <= () הוא סינטקסס חוקי והוא קיצור של {return x} <= ().

+ +

אנחנו אפילו יכולים לרשום את הקוד שלנו בצורה כזו, מאחר שהפונקציות רק מעביר את הארגומנטים שלהם בצורה ישירה, אין צורך באמת לשכבה נוספת של פונקציה:

+ +
chooseToppings().then(placeOrder).then(collectOrder).then(eatPizza).catch(failureCallback);
+ +

יחד עם זאת, סינטקס זה לא ניתן לשימוש שוב, ולא ממש ברור לקריאה. 

+ +
+

לתשומת לב: אנחנו אפילו יכולים לעשות שיפורים נוספים בסינטקס באמצעות הסינטקס של async/await, אשר נסקור אותו בהמשך המודול.

+
+ +

בבסיס שלהן, promises דומות למאזיני אירוע - event lisenters אך עם הבדלים ביניהם:

+ + + +

הסבר של הסינטקט הבסיסי של promise

+ +

Promises חשובות מאוד להבנה מכיוון שמרבית ה-Web API המודרניים משתמשים בהן בעבור פונקציות שעלולות לבצע פעולות ארוכות. 

+ +

בהמשך המאמר הזה אנחנו נראה כיצד לכתוב promises משלנו, אבל כאן אנחנו נסכתל על דוגמאות פשוטות שאנחנו ניתקל בהן ב-Web API שונים.

+ +

בדוגמא הראשונה שלנו, אנחנו נשתמש במתודת fetch(), על מנת להביא תמונה מהאינטרנט, במתודת {{domxref("Body.blob", "blob()")}} על מנת להמיר את התוכן הגולמי של התגובה שקיבלנו לאובייקט {{domxref("Blob")}} , ולאחר מכן נציג את אותו blob בתוך אלמנט {{htmlelement("img")}}. זהו מאוד דומה לדוגמא שהסתכלנו עליה במאמר הראשון במודול, אבל אנחנו נעשה את זה מעט שונה כך שאתם תבנו את ה-promise. 

+ +
    +
  1. +

    ראשית, הורידו את ה-HTML template ואת ה-image file שאנחנו נייבא. 

    +
  2. +
  3. +

    הוסיפו אלמנט {{htmlelement("script")}} בתחתית ה-{{htmlelement("body")}} בקובץ ה-HTML.

    +
  4. +
  5. +

    בתוך האלמנט {{HTMLElement("script")}} , הוסיפו את השורה הבאה: 

    +
  6. +
  7. +
    let promise = fetch('coffee.jpg');
    + +

    שורה זו קוראת למתודת ()fetch ומעבירה אליה כפרמטר את ה-URL של התמונה שאנחנו רוצים לייבא מהרשת. אנחנו מאחסנים את אובייקט ה-promise שיוחזר אלינו מ-()fetch בתוך משתנה שנקרא לו promise. כפי שאמרנו בעבר, האובייקט הזה מייצג מצב ביניים שבהתחלה הוא לא הצלחה ולא כישלון - מצב זה נקרא pending.

    +
  8. +
  9. על מנת להגיב להצלחה של הפעולה כאשר היא תקרה, במקרה הזה כאשר {{domxref("Response")}} תוחזר אלינו, אנחנו נפעיל את המתודת ()then. של אובייקט ה-promise. ה-callback בתוך בלוק הקוד של ()then. (שנקרא גם executor), ירוץ רק כאשר פעולת ה-promise תושלם בהצלחה ותחזיר אובייקט {{domxref("Response")}} - במונחי promise, כאשר ה-promise תגיע למצב של הושלמה, fulfilled. היא תעביר את האובייקט {{domxref("Response")}} כפרמטר. 
  10. +
  11. +
    +

    לתשומת לב: הדרך שבה הבלוק ()then. עובד היא דומה לדרך שבה אנחנו מוסיפים מאזין אירוע - event listener - לאובייקט באמצעות המתודה ()AddEventListener. מאזין האירוע לא ירוץ עד אשר האירוע יתרחש (ובאותה נשימה, כאשר ה-promise הושלמה בהצלחה). ההבדל העיקרי ביניהם הוא ש-()then. ירוץ רק פעם אחת בכל פעם שמשתמשים בו ואילו מאזין האירוע יכול להיות מופעל כמה פעמים. 

    +
    + +

    אנחנו מייד נריץ את מתודת  ()blob על התגובה הזו, על מנת לוודא שגוף התגובה הורד בהצלחה, וכאשר הוא זמין נהפוך אותו לאובייקט Blob שאנחנו יכולים לעשות איתו משהו. התוצאה של זה תוחזר לנו כך :

    + +
    response => response.blob()
    + +

    שזה קיצור של: 

    + +
    function(response) {
    +  return response.blob();
    +}
    + +

    עד כאן עם ההסבר, אנא הוסיפו את הקוד הבא מתחת לשורה הראשונה של JavaScript: 

    + +
    let promise2 = promise.then(response => response.blob());
    +
  12. +
  13. +

    כל קריאה ל-()then. יוצרת promise חדשה. זהו מאוד שימושי - מכיוון שמתודת -  ()blob מחזירה גם היא promise, אנחנו יכולים לטפל באובייקט ה-Blob שהיא מחזירה בעת ההשלמה שלו באמצעות הפעלה של מתודת ()then. על ה-promise השנייה. מכיוון שאנחנו רוצים לעשות משהו קצת יותר מורכב לאותו blob מאשר רק להריץ מתודה אחת עליו ולהחזיר את התוצאה, אנחנו צריכים לעטוף את גוף הפונקצייה בסוגריים מסולסלות - אחרת זה יגרום לשגיאה. הוסיפו את השורה הבאה מתחת לקוד הנוכחי שלכם: 

    +
  14. +
  15. +
    let promise3 = promise2.then(myBlob => {
    +
    +})
    +
  16. +
  17. +

    כעת, נכניס את הקוד הבא שהוא הפונקציה שתופעל, לתוך הסוגריים המסולסלות:

    + +
    let objectURL = URL.createObjectURL(myBlob);
    +let image = document.createElement('img');
    +image.src = objectURL;
    +document.body.appendChild(image);
    + +

    מה שעשינו כאן אנחנו מריצים בעצם מריצים מתודת {{domxref("URL.createObjectURL()")}} , מעבירים אליה כפרמרט את ה-Blob שהוחזר אלינו כאשר ה-promise השנייה הושלמה. זה מחזיר לנו URL שמצביע על האובייקט. לאחר מכן יצרנו אלמנט {{htmlelement("img")}} , וקבענו את ה-src שלו שיהיה שווה ל-URL של האובייקט ושייכנו אותו ל-DOM, כך שהתמונה תוצג על גבי הדף. 

    +
  18. +
+ +

אם תשמרו ותרעננו את הדף, אתם תראו שהתמונה מוצגת על גבי הדף. 

+ +
+

לתשומת לב:  אתם בטח תשימו לב שדוגמאות אלו ארוכות מדי בשביל פעולה פשוטה שיכולנו לבצע באמצעות יצירת אלמנט <img> וקביעת ה-src שלו לאותו URL של התמונה במקום לעשות זאת באמצעות ()fetch ובאמצעות ()blob. יחד עם זאת, דוגמא זו נועדה על מנת להסביר בפשטות את תהליך ה-promises.

+
+ +

תגובה לכישלון 

+ +

יש משהו חסר בדוגמא שלנו - כרגע, אין משהו שמגדיר כיצד להתמודד עם שגיאה כאשר ה-promise נכשלת, או rejects במונחים של promises. אנחנו יכולים להוסיף טיפול בשגיאה באמצעות הרצת מתודת ()catch. של ה-promise הקודמת:

+ +
let errorCase = promise3.catch(e => {
+  console.log('There has been a problem with your fetch operation: ' + e.message);
+});
+ + + +

To see this in action, try misspelling the URL to the image and reloading the page. The error will be reported in the console of your browser's developer tools.

+ +

This doesn't do much more than it would if you just didn't bother including the .catch() block at all, but think about it — this allows us to control error handling exactly how we want. In a real app, your .catch() block could retry fetching the image, or show a default image, or prompt the user to provide a different image URL, or whatever.

+ +
+

Note: You can see our version of the example live (see the source code also).

+
+ +

Chaining the blocks together

+ +

This is a very longhand way of writing this out; we've deliberately done this to help you understand what is going on clearly. As shown earlier on in the article, you can chain together .then() blocks (and also .catch() blocks). The above code could also be written like this (see also simple-fetch-chained.html on GitHub):

+ +
fetch('coffee.jpg')
+.then(response => response.blob())
+.then(myBlob => {
+  let objectURL = URL.createObjectURL(myBlob);
+  let image = document.createElement('img');
+  image.src = objectURL;
+  document.body.appendChild(image);
+})
+.catch(e => {
+  console.log('There has been a problem with your fetch operation: ' + e.message);
+});
+ +

Bear in mind that the value returned by a fulfilled promise becomes the parameter passed to the next .then() block's executor function.

+ +
+

Note: .then()/.catch() blocks in promises are basically the async equivalent of a try...catch block in sync code. Bear in mind that synchronous try...catch won't work in async code.

+
+ +

Promise terminology recap

+ +

There was a lot to cover in the above section, so let's go back over it quickly to give you a short guide that you can bookmark and use to refresh your memory in the future. You should also go over the above section again a few more time to make sure these concepts stick.

+ +
    +
  1. When a promise is created, it is neither in a success or failure state. It is said to be pending.
  2. +
  3. When a promise returns, it is said to be resolved. +
      +
    1. A successfully resolved promise is said to be fulfilled. It returns a value, which can be accessed by chaining a .then() block onto the end of the promise chain. The executor function inside the .then() block will contain the promise's return value.
    2. +
    3. An unsuccessful resolved promise is said to be rejected. It returns a reason, an error message stating why the promise was rejected. This reason can be accessed by chaining a .catch() block onto the end of the promise chain.
    4. +
    +
  4. +
+ +

Running code in response to multiple promises fulfilling

+ +

The above example showed us some of the real basics of using promises. Now let's look at some more advanced features. For a start, chaining processes to occur one after the other is all fine, but what if you want to run some code only after a whole bunch of promises have all fulfilled?

+ +

You can do this with the ingeniously named Promise.all() static method. This takes an array of promises as an input parameter and returns a new Promise object that will fulfill only if and when all promises in the array fulfill. It looks something like this:

+ +
Promise.all([a, b, c]).then(values => {
+  ...
+});
+ +

If they all fulfill, then chained .then() block's executor function will be passed an array containing all those results as a parameter. If any of the promises passed to Promise.all() reject, the whole block will reject.

+ +

This can be very useful. Imagine that we’re fetching information to dynamically populate a UI feature on our page with content. In many cases, it makes sense to receive all the data and only then show the complete content, rather than displaying partial information.

+ +

Let's build another example to show this in action.

+ +
    +
  1. +

    Download a fresh copy of our page template, and again put a <script> element just before the closing </body> tag.

    +
  2. +
  3. +

    Download our source files (coffee.jpg, tea.jpg, and description.txt), or feel free to substitute your own.

    +
  4. +
  5. +

    In our script we'll first define a function that returns the promises we want to send to Promise.all(). This would be easy if we just wanted to run the Promise.all() block in response to three fetch() operations completing. We could just do something like:

    + +
    let a = fetch(url1);
    +let b = fetch(url2);
    +let c = fetch(url3);
    +
    +Promise.all([a, b, c]).then(values => {
    +  ...
    +});
    + +

    When the promise is fulfilled, the values passed into the fullfillment handler would contain three Response objects, one for each of the fetch() operations that have completed.

    + +

    However, we don't want to do this. Our code doesn't care when the fetch() operations are done. Instead, what we want is the loaded data. That means we want to run the Promise.all() block when we get back usable blobs representing the images, and a usable text string. We can write a function that does this; add the following inside your <script> element:

    + +
    function fetchAndDecode(url, type) {
    +  return fetch(url).then(response => {
    +    if (type === 'blob') {
    +      return response.blob();
    +    } else if (type === 'text') {
    +      return response.text();
    +    }
    +  })
    +  .catch(e => {
    +    console.log('There has been a problem with your fetch operation: ' + e.message);
    +  });
    +}
    + +

    This looks a bit complex, so let's run through it step by step:

    + +
      +
    1. First of all we define the function, passing it a URL and a string representing the type of resource it is fetching.
    2. +
    3. Inside the function body, we have a similar structure to what we saw in the first example — we call the fetch() function to fetch the resource at the specified URL, then chain it onto another promise that returns the decoded (or "read") response body. This was always the blob() method in the previous example.
    4. +
    5. However, two things are different here: +
        +
      • First of all, the second promise we return is different depending on what the type value is. Inside the executor function we include a simple if ... else if statement to return a different promise depending on what type of file we need to decode (in this case we've got a choice of blob or text, but it would be easy to extend this to deal with other types as well).
      • +
      • Second, we have added the return keyword before the fetch() call. The effect this has is to run the entire chain and then run the final result (i.e. the promise returned by blob() or text()) as the return value of the function we've just defined. In effect, the return statements pass the results back up the chain to the top.
      • +
      +
    6. +
    7. +

      At the end of the block, we chain on a .catch() call, to handle any error cases that may come up with any of the promises passed in the array to .all(). If any of the promises reject, the catch block will let you know which one had a problem. The .all() block (see below) will still fulfill, but just won't display the resources that had problems. If you wanted the .all to reject, you'd have to chain the .catch() block on to the end of there instead.

      +
    8. +
    + +

    The code inside the function body is async and promise-based, therefore in effect the entire function acts like a promise — convenient.

    +
  6. +
  7. +

    Next, we call our function three times to begin the process of fetching and decoding the images and text, and store each of the returned promises in a variable. Add the following below your previous code:

    + +
    let coffee = fetchAndDecode('coffee.jpg', 'blob');
    +let tea = fetchAndDecode('tea.jpg', 'blob');
    +let description = fetchAndDecode('description.txt', 'text');
    +
  8. +
  9. +

    Next, we will define a Promise.all() block to run some code only when all three of the promises stored above have successfully fulfilled. To begin with, add a block with an empty executor inside the .then() call, like so:

    + +
    Promise.all([coffee, tea, description]).then(values => {
    +
    +});
    + +

    You can see that it takes an array containing the promises as a parameter. The executor will only run when all three promises resolve; when that happens, it will be passed an array containing the results from the individual promises (i.e. the decoded response bodies), kind of like [coffee-results, tea-results, description-results].

    +
  10. +
  11. +

    Last of all, add the following inside the executor. Here we use some fairly simple sync code to store the results in separate variables (creating object URLs from the blobs), then display the images and text on the page.

    + +
    console.log(values);
    +// Store each value returned from the promises in separate variables; create object URLs from the blobs
    +let objectURL1 = URL.createObjectURL(values[0]);
    +let objectURL2 = URL.createObjectURL(values[1]);
    +let descText = values[2];
    +
    +// Display the images in <img> elements
    +let image1 = document.createElement('img');
    +let image2 = document.createElement('img');
    +image1.src = objectURL1;
    +image2.src = objectURL2;
    +document.body.appendChild(image1);
    +document.body.appendChild(image2);
    +
    +// Display the text in a paragraph
    +let para = document.createElement('p');
    +para.textContent = descText;
    +document.body.appendChild(para);
    +
  12. +
  13. +

    Save and refresh and you should see your UI components all loaded, albeit in a not particularly attractive way!

    +
  14. +
+ +

The code we provided here for displaying the items is fairly rudimentary, but works as an explainer for now.

+ +
+

Note: If you get stuck, you can compare your version of the code to ours, to see what it is meant to look like — see it live, and see the source code.

+
+ +
+

Note: If you were improving this code, you might want to loop through a list of items to display, fetching and decoding each one, and then loop through the results inside Promise.all(), running a different function to display each one depending on what the type of code was. This would make it work for any number of items, not just three.

+ +

In addition, you could determine what the type of file is being fetched without needing an explicit type property. You could for example check the {{HTTPHeader("Content-Type")}} HTTP header of the response in each case using response.headers.get("content-type"), and then react accordingly.

+
+ +

Running some final code after a promise fulfills/rejects

+ +

There will be cases where you want to run a final block of code after a promise completes, regardless of whether it fulfilled or rejected. Previously you'd have to include the same code in both the .then() and .catch() callbacks, for example:

+ +
myPromise
+.then(response => {
+  doSomething(response);
+  runFinalCode();
+})
+.catch(e => {
+  returnError(e);
+  runFinalCode();
+});
+ +

In more recent modern browsers, the .finally() method is available, which can be chained onto the end of your regular promise chain allowing you to cut down on code repetition and do things more elegantly. The above code can now be written as follows:

+ +
myPromise
+.then(response => {
+  doSomething(response);
+})
+.catch(e => {
+  returnError(e);
+})
+.finally(() => {
+  runFinalCode();
+});
+ +

For a real example, take a look at our promise-finally.html demo (see the source code also). This works exactly the same as the Promise.all() demo we looked at in the above section, except that in the fetchAndDecode() function we chain a finally() call on to the end of the chain:

+ +
function fetchAndDecode(url, type) {
+  return fetch(url).then(response => {
+    if(type === 'blob') {
+      return response.blob();
+    } else if(type === 'text') {
+      return response.text();
+    }
+  })
+  .catch(e => {
+    console.log(`There has been a problem with your fetch operation for resource "${url}": ` + e.message);
+  })
+  .finally(() => {
+    console.log(`fetch attempt for "${url}" finished.`);
+  });
+}
+ +

This logs a simple message to the console to tell us when each fetch attempt has finished.

+ +
+

Note: finally() allows you to write async equivalents to try/catch/finally in async code.

+
+ +

Building your own custom promises

+ +

The good news is that, in a way, you've already built your own promises. When you've chained multiple promises together with .then() blocks, or otherwise combined them to create custom functionality, you are already making your own custom async promise-based functions. Take our fetchAndDecode() function from the previous examples, for example.

+ +

Combining different promise-based APIs together to create custom functionality is by far the most common way you'll do custom things with promises, and shows the flexibility and power of basing most modern APIs around the same principle. There is another way, however.

+ +

Using the Promise() constructor

+ +

It is possible to build your own promises using the Promise() constructor. The main situation in which you'll want to do this is when you've got code based on an an old-school asynchronous API that is not promise-based, which you want to promis-ify. This comes in handy when you need to use existing, older project code, libraries, or frameworks along with modern promise-based code.

+ +

Let's have a look at a simple example to get you started — here we wrap a setTimeout() call with a promise — this runs a function after two seconds that resolves the promise (using the passed resolve() call) with a string of "Success!".

+ +
let timeoutPromise = new Promise((resolve, reject) => {
+  setTimeout(function(){
+    resolve('Success!');
+  }, 2000);
+});
+ +

resolve() and reject() are functions that you call to fulfill or reject the newly-created promise. In this case, the promise fulfills with a string of "Success!".

+ +

So when you call this promise, you can chain a .then() block onto the end of it and it will be passed a string of "Success!". In the below code we simply alert that message:

+ +
timeoutPromise
+.then((message) => {
+   alert(message);
+})
+ +

or even just

+ +
timeoutPromise.then(alert);
+
+ +

Try running this live to see the result (also see the source code).

+ +

The above example is not very flexible — the promise can only ever fulfill with a single string, and it doesn't have any kind of reject() condition specified (admittedly, setTimeout() doesn't really have a fail condition, so it doesn't matter for this simple example).

+ +
+

Note: Why resolve(), and not fulfill()? The answer we'll give you for now is it's complicated.

+
+ +

Rejecting a custom promise

+ +

We can create a promise that rejects using the reject() method — just like resolve(), this takes a single value, but in this case it is the reason to reject with, i.e., the error that will be passed into the .catch() block.

+ +

Let's extend the previous example to have some reject() conditions as well as allowing different messages to be passed upon success.

+ +

Take a copy of the previous example, and replace the existing timeoutPromise() definition with this:

+ +
function timeoutPromise(message, interval) {
+  return new Promise((resolve, reject) => {
+    if (message === '' || typeof message !== 'string') {
+      reject('Message is empty or not a string');
+    } else if (interval < 0 || typeof interval !== 'number') {
+      reject('Interval is negative or not a number');
+    } else {
+      setTimeout(function(){
+        resolve(message);
+      }, interval);
+    }
+  });
+};
+ +

Here we are passing two arguments into a custom function — a message to do something with, and the time interval to pass before doing the thing. Inside the function we then return a new Promise object — invoking the function will return the promise we want to use.

+ +

Inside the Promise constructor, we do a number of checks inside if ... else structures:

+ +
    +
  1. First of all we check to see if the message is appropriate for being alerted. If it is an empty string or not a string at all, we reject the promise with a suitable error message.
  2. +
  3. Next, we check to see if the interval is an appropriate interval value. If it is negative or not a number, we reject the promise with a suitable error message.
  4. +
  5. Finally, if the parameters both look OK, we resolve the promise with the specified message after the specified interval has passed using setTimeout().
  6. +
+ +

Since the timeoutPromise() function returns a Promise, we can chain .then(), .catch(), etc. onto it to make use of its functionality. Let's use it now — replace the previous timeoutPromise usage with this one:

+ +
timeoutPromise('Hello there!', 1000)
+.then(message => {
+   alert(message);
+})
+.catch(e => {
+  console.log('Error: ' + e);
+});
+ +

When you save and run the code as is, after one second you'll get the message alerted. Now try setting the message to an empty string or the interval to a negative number, for example, and you'll be able to see the promise reject with the appropriate error messages! You could also try doing something else with the resolved message rather than just alerting it.

+ +
+

Note: You can find our version of this example on GitHub as custom-promise2.html (see also the source code).

+
+ +

A more real-world example

+ +

The above example was kept deliberately simple to make the concepts easy to understand, but it is not really very async. The asynchronous nature is basically faked using setTimeout(), although it does still show that promises are useful for creating a custom function with sensible flow of operations, good error handling, etc.

+ +

One example we'd like to invite you to study, which does show a useful async application of the Promise() constructor, is Jake Archibald's idb library. This takes the IndexedDB API, which is an old-style callback-based API for storing and retrieving data on the client-side, and allows you to use it with promises. If you look at the main library file you'll see the same kind of techniques we discussed above being used there. The following block converts the basic request model used by many IndexedDB methods to use promises:

+ +
function promisifyRequest(request) {
+  return new Promise(function(resolve, reject) {
+    request.onsuccess = function() {
+      resolve(request.result);
+    };
+
+    request.onerror = function() {
+      reject(request.error);
+    };
+  });
+}
+ +

This works by adding a couple of event handlers that fulfill and reject the promise at appropriate times:

+ + + +

Conclusion

+ +

Promises are a good way to build asynchronous applications when we don’t know the return value of a function or how long it will take to return. They make it easier to express and reason about sequences of asynchronous operations without deeply nested callbacks, and they support a style of error handling that is similar to the synchronous try...catch statement.

+ +

Promises work in the latest versions of all modern browsers; the only place where promise support will be a problem is in Opera Mini and IE11 and earlier versions.

+ +

We didn't touch on all promise features in this article, just the most interesting and useful ones. As you start to learn more about promises, you'll come across further features and techniques.

+ +

Most modern Web APIs are promise-based, so you'll need to understand promises to get the most out of them. Among those APIs are WebRTC, Web Audio API, Media Capture and Streams, and many more. Promises will be more and more important as time goes on, so learning to use and understand them is an important step in learning modern JavaScript.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Timeouts_and_intervals", "Learn/JavaScript/Asynchronous/Async_await", "Learn/JavaScript/Asynchronous")}}

+ +

במודול זה

+ + diff --git a/files/he/learn/javascript/asynchronous/timeouts_and_intervals/index.html b/files/he/learn/javascript/asynchronous/timeouts_and_intervals/index.html new file mode 100644 index 0000000000..2d97d2827d --- /dev/null +++ b/files/he/learn/javascript/asynchronous/timeouts_and_intervals/index.html @@ -0,0 +1,651 @@ +--- +title: 'Cooperative asynchronous JavaScript: Timeouts and intervals' +slug: Learn/JavaScript/Asynchronous/Timeouts_and_intervals +translation_of: Learn/JavaScript/Asynchronous/Timeouts_and_intervals +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Introducing", "Learn/JavaScript/Asynchronous/Promises", "Learn/JavaScript/Asynchronous")}}
+ +

+ במאמר זה אנחנו נסתכל על מתודות מסורתיות שיש ב-JavaScript, בעבור הרצה של קוד באופן א-סינכרוני לאחר שזמן מסויים עבר או באינטרוול מסויים (כלומר לקבוע מספר פעמים שירוץ בכל פרק זמן מסויים), נדון בשימושים שלהם ומה הסוגיות הטבועות בהם. + +

+ + + + + + + + + + + + +
ידע מוקדם:Basic computer literacy, a reasonable understanding of JavaScript fundamentals.
מטרה: + הבנה של לולאות א-סינכרוניות ואינטרוולים ולמה הם משמים.
+ +

הקדמה

+ +

+ במשך זמן רב, פלטפורמת ה-web העניקה למפתחי JavaScript מספר של פונקציות שאפשרו לה להריץ קוד באופן א-סינכרוני, כך שהקוד ירוץ לאחר זמן מסויים שעבר או להריץ קוד מסויים באופן א-סינכרוני,ע ם הפרש זמן מסויים בין כל ריצה שלו, עד שאנחנו נגיד לו לעצור. אלו הם :

+ +
+
setTimeout()
+
+ מריץ בלוק קוד מסויים פעם אחת לאחר שזמן מסויים עבר.
+
setInterval()
+
+ מריץ בלוק קוד מסויים באופן חוזר, עם הפרש של זמן מסויים בין כל ריצה.
+
requestAnimationFrame()
+
+ זוהי גרסה מודרנית ל-setInterval(). היא מריצה בלוק קוד מסויים לפני שהדפדפן צובע מחדש את התצוגה, כך שמתאפשרת לאניממציה לרוץ במסגרת מתאימה ללא קשר לסביבה בה היא פועלת. +
+
+ +

+ הקוד הא-סינכרוני שנכתב באמצעות פונקציות אלו בעצם ירוץ על ה-00000, אבל כן התאפשר לנו להריץ קוד אחר בין כל ריצה שלהם במידה מסוייתמ, תלוי כמה הפונקציות שנכתוב יעשו שימוש רב במעבד. בכל מקרה, הפונקציות הללו משמשות אנימציות קבועות ועוד תהליכי רקע על אתר אינטרנט או יישום אינטרנטר. בחלקים הבאים של המאמר אנחנו נגע בכל אחת מהן ולמה הן משמשות. .

+ +

setTimeout()

+ +

+ כפי שאמרנו למעלה, setTimeout() מריצה בלוק קוד מסויים פעם אחת, לאחר שזמן מסויים שהגדרנו לה חלף. היא מקבלת את הפרמטרים הבאים:

+ + + +
+

לתשומת לב: + מכיוון ש-0000000 מורצות ביחד, אין כל הבטחה שהן יופעלו במדוייק לאחר הזמן שהגדרנו. במקום, הם ייקראו לאחר שהזמן שהגדרנו חלף, לפחות. + + Because timeout callbacks are executed cooperatively, there's no guarantee that they will be called after exactly the specified amount of time. Instead, they will be called after at least that much time has elapsed. + + + Timeout handlers לא יכולים לרוץ עד אשר ה-main thread מגיע לנקודה בריצה שלו שם הוא עובר על מטפלים אלו למצוא את אלו שהוא צריך להריץ אותם. שה-00000 +

+
+ +

+ בדוגמא הבאה, הדפדפן יחכה שתי שניות לפני שיריץ את הפונקציה האנונימית, ואז יציג את הודעת ה-alert. +e (ראו כדף אינטרנט, וכן את קוד המקור):

+ +
let myGreeting = setTimeout(function() {
+  alert('Hello, Mr. Universe!');
+}, 2000)
+ +

+ הפונקציות שאנחנו מציינים לא חייבות להיות אנונימיות. אנחנו יכולים לתת לפונקציה שלנו שם ואפילו להגדיר אותה במקום אחר, ואז להעביר הפנייה לפונקציה בתוך ה- setTimeout() . הגרסאות הבאות של הקוד שלנו הם שוות לראשונה: + + he functions we specify don't have to be anonymous. We can give our function a name, and can even define it somewhere else and pass a function reference to the setTimeout(). The following two versions of our code snippet are equivalent to the first one:

+ +
// With a named function
+let myGreeting = setTimeout(function sayHi() {
+  alert('Hello, Mr. Universe!');
+}, 2000)
+
+// With a function defined separately
+function sayHi() {
+  alert('Hello Mr. Universe!');
+}
+
+let myGreeting = setTimeout(sayHi, 2000);
+ +

+ זה יכול להיות שימושי כאשר יש לנו פונקציה שצריכה להיקרא/להיות מופעלת גם מתוך -timeout וגם בתגובה לאירוע, לדוגמא. אבל, זה גם יכול לעזור לנו להשאיר את הקוד שלנו מסודר, במיוחד אם אחרי ה-timeout callback יש לנו יותר מכמה שורות קוד. +

+ +

setTimeout() + מחזירה ערך מזהה שיכול לשמש לשם הפנייה לאותו timeout לאחר מכן, אם נרצה לדוגמא לעצור את ה-timeout. ראו {{anch("Clearing timeouts")}} בהמשך על מנת ללמוד כיצד לעשות זאת. + + +

+ +

העברת פרמטרים לפונקציית setTimeout()

+ +

+ כל פרמטר שנרצה להעביר לפונקציה שתרוף בתוך ה-setTimeout(), יהיו חייבים להיות מועברים כפרמטרים נוספוים לפונקציית ה-setTimeout(), וזאת בסוף הרשימת פרמטרים. לדוגמא, אנחנו יכולים כתוב מחדש את הפונקציה הקודמת שלנו כך שהיא תגיד hi לכל שם שיועבר אליה +:

+ +
function sayHi(who) {
+  alert('Hello ' + who + '!');
+}
+ +

+ השם של ה-person יכול להיות מועבר כפרמטר שלישי לתוך ה-setTimeout() + +:

+ +
let myGreeting = setTimeout(sayHi, 2000, 'Mr. Universe');
+ +

מחיקת Timeouts

+ +

+ לבסוף, אם timeout נוצר, אנחנו יכולים לבטל אותו לפני שהזמן שהגדרנו לו הסתיים באמצעשות שימוש ב-clearTimeout() והעברה של אותו ערך מזהה של ה-setTimeout() כפרמטר. כך, על מנת לבטל את ה-setTimeout() בדוגמא למעלה, אנחנו צריכים לרשום משהו כזה: +

+ +
clearTimeout(myGreeting);
+ +
+

לתשומת לב: ראו greeter-app.html + לדוגמא יותר מעניינת אשר מאפשרת לכן לקבוע את השם של האדם שנגיד לו שלום בטופס, ואז לבטל את הברכה באמצעו תכפתור אחג. (קוד המקור).

+
+ +

setInterval()

+ +

setTimeout() עובדת מצוים כאשר אנחנו צריכים להריץ בלוק קוד מסויים פעם אחת לאחר אינטרוול זמן שעבר. אבל מה קורה כאשר אנחנו רוצים להריץ קוד מסויים שוב ושוב, כמו במקרה של אנימציות?

+ +

כאן נכנס לתמונה setInterval() . + פונקציה זו עובדת בצורה דומה ל-setTimeout(), למעט העובדה שהפונקציה שאנחנו מעבירים כפרמטר ראשון, תרוץ באופן חוזר ונשנה לכל הפחות בכל משך הזמן שהוגדר לה (גם כן במילישניות), ולא רק פעם אחת. אנחנו גם יכולים להעביר לה את הפרמטרים הדרושים לפונקציה שתרוץ. +.

+ +

+ נראה דוגמא על מנת להמחיש את העניין. הפונקציה הבא יוצרת אובייקט Date() חדש, מחלצת חרוזת זמן מתוכו באמצעות שימוש ב- toLocaleTimeString() ציגה את זה לממשק המתשמש. לאחר מכן אנחנו מריצים פונקציה אחת לשנייה באמצעות שימוש ב-setInterval() + על מנת ליצור את האפשר של שעון דיגיטלי שמעדכן את עצמו כל שנייה. + (ראו כדף אינטרנט, ואת also קוד המקור):

+ +
function displayTime() {
+   let date = new Date();
+   let time = date.toLocaleTimeString();
+   document.getElementById('demo').textContent = time;
+}
+
+const createClock = setInterval(displayTime, 1000);
+ +

בדיוק כמו setTimeout(), setInterval() מחזירה ערך מזהה כך שאנחנו יכולים להשתמש בו בהמשך על מנת למחוק את ה-interval.

+ +

מחיקת intervals

+ +

setInterval() תמשיך לרוץ באופן מתמשך וקבוע, אלא אם אנחנו נעשה איתה משהו - + אנחנו נרצה אולי דרך לעצור משימות כאלו, אחרת אנחנו נקבל שגיאות השהדפדפן לא מצליח להשלים גרסאות נוספות של המשימה הזו, או שהאניממציה שמטופלת על ידי המשימה הזו הסתיימה. אנחנו יכולים לעשות זאת באותה דרך שבה אנחנו מסיימים setInterval() - באמצעות העבר הערך המזהה שהוחזר לנו בהפעלה של setInterval() לפונקציה clearInterval(): + +

+ +
const myInterval = setInterval(myFunction, 2000);
+
+clearInterval(myInterval);
+ +

למידה עצמאית: יצירה של שעון עצר

+ +

לאחר שעברנו על פונקציות אלו, נסו לאתגר את עצמכם במשימה זו. עשו עותקשל הדוגמא שלנו שנמצא ב- setInterval-clock.html ושנו אותה כך שתהיה שעון סטופר.

+ +

+ אתם צריכים להציג את הזמן כמו בדוגמא הקודמת, רק שבתרגיל זה אתם תצטרכו:

+ + + +

רמזים:

+ + + +
+

Note: If you get stuck, you can find our version here (see the source code also).

+
+ +

Things to keep in mind about setTimeout() and setInterval()

+ +

There are a few things to keep in mind when working with setTimeout() and setInterval(). Let's review these now.

+ +

Recursive timeouts

+ +

There is another way we can use setTimeout(): We can call it recursively to run the same code repeatedly, instead of using setInterval().

+ +

The below example uses a recursive setTimeout() to run the passed function every 100 milliseconds:

+ +
let i = 1;
+
+setTimeout(function run() {
+  console.log(i);
+  i++;
+  setTimeout(run, 100);
+}, 100);
+ +

Compare the above example to the following one — this uses setInterval() to accomplish the same effect:

+ +
let i = 1;
+
+setInterval(function run() {
+  console.log(i);
+  i++
+}, 100);
+ +

How do recursive setTimeout() and setInterval() differ?

+ +

The difference between the two versions of the above code is a subtle one.

+ + + +

When your code has the potential to take longer to run than the time interval you’ve assigned, it’s better to use recursive setTimeout() — this will keep the time interval constant between executions regardless of how long the code takes to execute, and you won't get errors.

+ +

Immediate timeouts

+ +

Using 0 as the value for setTimeout() schedules the execution of the specified callback function as soon as possible but only after the main code thread has been run.

+ +

For instance, the code below (see it live) outputs an alert containing "Hello", then an alert containing "World" as soon as you click OK on the first alert.

+ +
setTimeout(function() {
+  alert('World');
+}, 0);
+
+alert('Hello');
+ +

This can be useful in cases where you want to set a block of code to run as soon as all of the main thread has finished running — put it on the async event loop, so it will run straight afterwards.

+ +

Clearing with clearTimeout() or clearInterval()

+ +

clearTimeout() and clearInterval() both use the same list of entries to clear from. Interestingly enough, this means that you can use either method to clear a setTimeout() or setInterval().

+ +

For consistency, you should use clearTimeout() to clear setTimeout() entries and clearInterval() to clear setInterval() entries. This will help to avoid confusion.

+ +

requestAnimationFrame()

+ +

requestAnimationFrame() is a specialized looping function created for running animations efficiently in the browser. It is basically the modern version of setInterval() — it executes a specified block of code before the browser next repaints the display, allowing an animation to be run at a suitable frame rate regardless of the environment it is being run in.

+ +

It was created in response to perceived problems with setInterval(), which for example doesn't run at a frame rate optimized for the device, sometimes drops frames, continues to run even if the tab is not the active tab or the animation is scrolled off the page, etc. Read more about this on CreativeJS.

+ +
+

Note: You can find examples of using requestAnimationFrame() elsewhere in the course — see for example Drawing graphics, and Object building practice.

+
+ +

The method takes as an argument a callback to be invoked before the repaint. This is the general pattern you'll see it used in:

+ +
function draw() {
+   // Drawing code goes here
+   requestAnimationFrame(draw);
+}
+
+draw();
+ +

The idea is that you define a function in which your animation is updated (e.g. your sprites are moved, score is updated, data is refreshed, or whatever), then you call it to start the process off. At the end of the function block you call requestAnimationFrame() with the function reference passed as the parameter, and this instructs the browser to call the function again on the next display repaint. This is then run continuously, as we are calling requestAnimationFrame() recursively.

+ +
+

Note: If you want to perform some kind of simple constant DOM animation, CSS Animations are probably faster as they are calculated directly by the browser's internal code rather than JavaScript. If however you are doing something more complex and involving objects that are not directly accessible inside the DOM (such as 2D Canvas API or WebGL objects), requestAnimationFrame() is the better option in most cases.

+
+ +

How fast does your animation run?

+ +

The smoothness of your animation is directly dependent on your animation's frame rate and it is measured in frames per second (fps). The higher this number is, the smoother your animation will look, to a point.

+ +

Since most screens have a refresh rate of 60Hz, the fastest frame rate you can aim for is 60 frames per second (FPS) when working with web browsers. However, more frames means more processing, which can often cause stuttering and skipping — also known as dropping frames, or jank.

+ +

If you have a monitor with a 60Hz refresh rate and you want to achieve 60 FPS you have about 16.7 milliseconds (1000 / 60) to execute your animation code to render each frame. This is a reminder that we need to be mindful of the amount of code that we try to run for each pass through the animation loop.

+ +

requestAnimationFrame() always tries to get as close to this magic 60 FPS value as possible, although sometimes it isn't possible — if you have a really complex animation and you are running it on a slow computer, your frame rate will be less. requestAnimationFrame() will always do the best it can with what it has available.

+ +

How does requestAnimationFrame() differ from setInterval() and setTimeout()?

+ +

Let's talk a little bit more about how the requestAnimationFrame() method differs from the other methods we looked at earlier. Looking at our code from above:

+ +
function draw() {
+   // Drawing code goes here
+   requestAnimationFrame(draw);
+}
+
+draw();
+ +

Let's now see how we'd do the same thing using setInterval():

+ +
function draw() {
+   // Drawing code goes here
+}
+
+setInterval(draw, 17);
+ +

As we said before, we don't specify a time interval for requestAnimationFrame(); it just runs it as quickly and smoothly as possible in the current conditions. The browser also doesn't waste time running it if the animation is offscreen for some reason, etc.

+ +

setInterval() on the other hand requires an interval to be specified. We arrived at our final value of 17 via the formula 1000 milliseconds / 60Hz, and then rounded it up. Rounding up is a good idea, as if you rounded down the browser might try to run the animation faster than 60fps, and it wouldn't make any difference to the smoothness of the animation anyway. As we said before, 60Hz is the standard refresh rate.

+ +

Including a timestamp

+ +

The actual callback passed to the requestAnimationFrame() function can be given a parameter too — a timestamp value that represents the time since the requestAnimationFrame() started running. This is useful as it allows you to run things at specific times and at a constant pace, regardless of how fast or slow your device might be. The general pattern you'd use looks something like this:

+ +
let startTime = null;
+
+function draw(timestamp) {
+    if(!startTime) {
+      startTime = timestamp;
+    }
+
+   currentTime = timestamp - startTime;
+
+   // Do something based on current time
+
+   requestAnimationFrame(draw);
+}
+
+draw();
+ +

Browser support

+ +

requestAnimationFrame() is supported in slightly more recent browsers than setInterval()/setTimeout() — most interestingly it is available in Internet Explorer 10 and above. So unless you need to support older versions of IE with your code, there is little reason to not use requestAnimationFrame().

+ +

A simple example

+ +

Enough with the theory; let's go through and build our own requestAnimationFrame() example. We're going to create a simple "spinner animation", the kind you might see displayed in an app when it is busy connecting to the server, etc.

+ +
+

Note: In a real world example, you should probably use CSS animations to run this kind of simple animation. However, this kind of example is very useful to demonstrate requestAnimationFrame() usage, and you'd be more like to use this kind of technique when doing something more complex such as updating the display of a game on each frame.

+
+ +
    +
  1. +

    First of all, grab a basic HTML template such as this one.

    +
  2. +
  3. +

    Put an empty {{htmlelement("div")}} element inside the {{htmlelement("body")}}, then add a ↻ character inside it. This is a circular arrow character that will act as our spinner for this simple example.

    +
  4. +
  5. +

    Apply the following CSS to the HTML template in whatever way you prefer. This sets a red background on the page, sets the <body> height to 100% of the {{htmlelement("html")}} height, and centers the <div> inside the <body>, horizontally and vertically.

    + +
    html {
    +  background-color: white;
    +  height: 100%;
    +}
    +
    +body {
    +  height: inherit;
    +  background-color: red;
    +  margin: 0;
    +  display: flex;
    +  justify-content: center;
    +  align-items: center;
    +}
    +
    +div {
    +  display: inline-block;
    +  font-size: 10rem;
    +}
    +
  6. +
  7. +

    Insert a {{htmlelement("script")}} element just above the </body> tag.

    +
  8. +
  9. +

    Insert the following JavaScript inside your <script> element. Here we're storing a reference to the <div> inside a constant, setting a rotateCount variable to 0, setting an uninitialized variable that will later be used to contain a reference to the requestAnimationFrame() call, and setting a startTime variable to null, which will later be used to store the start time of the requestAnimationFrame().

    + +
    const spinner = document.querySelector('div');
    +let rotateCount = 0;
    +let startTime = null;
    +let rAF;
    +
    +
  10. +
  11. +

    Below the previous code, insert a draw() function that will be used to contain our animation code, which includes the timestamp parameter:

    + +
    function draw(timestamp) {
    +
    +}
    +
  12. +
  13. +

    Inside draw(), add the following lines. Here we define the start time if it is not defined already (this will only happen on the first loop iteration), and set the rotateCount to a value to rotate the spinner by (the current timestamp, take the starting timestamp, divided by three so it doesn't go too fast):

    + +
      if (!startTime) {
    +   startTime = timestamp;
    +  }
    +
    +  rotateCount = (timestamp - startTime) / 3;
    +
    +
  14. +
  15. +

    Below the previous line inside draw(), add the following block — this checks to see if the value of rotateCount is above 359 (e.g. 360, a full circle). If so, it sets the value to its modulo of 360 (i.e. the remainder left over when the value is divided by 360) so the circle animation can continue uninterrupted, at a sensible, low value. Note that this isn't strictly necessary, but it is easier to work with values of 0-359 degrees than values like "128000 degrees".

    + +
    if (rotateCount > 359) {
    +  rotateCount %= 360;
    +}
    +
  16. +
  17. Next, below the previous block add the following line to actually rotate the spinner: +
    spinner.style.transform = 'rotate(' + rotateCount + 'deg)';
    +
  18. +
  19. +

    At the very bottom inside the draw() function, insert the following line. This is the key to the whole operation — we are setting the variable we defined earlier to an active requestAnimation() call that takes the draw() function as its parameter. This starts the animation off, constantly running the draw() function at a rate of as close to 60 FPS as possible.

    + +
    rAF = requestAnimationFrame(draw);
    +
  20. +
+ +
+

Note: You can find this example live on GitHub (see the source code also).

+
+ +

Clearing a requestAnimationFrame() call

+ +

Clearing a requestAnimationFrame() call can be done by calling the corresponding cancelAnimationFrame() method (note, "cancel" not "clear" as with the "set..." methods), passing it the value returned by the requestAnimationFrame() call to cancel, which we stored in a variable called rAF:

+ +
cancelAnimationFrame(rAF);
+ +

Active learning: Starting and stopping our spinner

+ +

In this exercise, we'd like you to test out the cancelAnimationFrame() method by taking our previous example and updating it, adding an event listener to start and stop the spinner when the mouse is clicked anywhere on the page.

+ +

Some hints:

+ + + +
+

Note: Try this yourself first; if you get really stuck, check out of our live example and source code.

+
+ +

Throttling a requestAnimationFrame() animation

+ +

One limitation of requestAnimationFrame() is that you can't choose your frame rate. This isn't a problem most of the time, as generally you want your animation to run as smoothly as possible, but what about when you want to create an old school, 8-bit-style animation?

+ +

This was a problem for example in the Monkey Island-inspired walking animation from our Drawing Graphics article:

+ +

{{EmbedGHLiveSample("learning-area/javascript/apis/drawing-graphics/loops_animation/7_canvas_walking_animation.html", '100%', 260)}}

+ +

In this example we have to animate both the position of the character on the screen, and the sprite being shown. There are only 6 frames in the sprite's animation; if we showed a different sprite frame for every frame displayed on the screen by requestAnimationFrame(), Guybrush would move his limbs too fast and the animation would look ridiculous. We therefore throttled the rate at which the sprite cycles its frames using the following code:

+ +
if (posX % 13 === 0) {
+  if (sprite === 5) {
+    sprite = 0;
+  } else {
+    sprite++;
+  }
+}
+ +

So we are only cycling a sprite once every 13 animation frames. OK, so it's actually about every 6.5 frames, as we update posX (character's position on the screen) by two each frame:

+ +
if(posX > width/2) {
+  newStartPos = -((width/2) + 102);
+  posX = Math.ceil(newStartPos / 13) * 13;
+  console.log(posX);
+} else {
+  posX += 2;
+}
+ +

This is the code that works out how to update the position in each animation frame.

+ +

The method you use to throttle your animation will depend on your particular code. For example, in our spinner example we could make it appear to move slower by only increasing our rotateCount by one on each frame instead of two.

+ +

Active learning: a reaction game

+ +

For our final section of this article, we'll create a 2-player reaction game. Here we have two players, one of whom controls the game using the A key, and the other with the L key.

+ +

When the Start button is pressed, a spinner like the one we saw earlier is displayed for a random amount of time between 5 and 10 seconds. After that time, a message will appear saying "PLAYERS GO!!" — once this happens, the first player to press their control button will win the game.

+ +

{{EmbedGHLiveSample("learning-area/javascript/asynchronous/loops-and-intervals/reaction-game.html", '100%', 500)}}

+ +

Let's work through this.

+ +
    +
  1. +

    First of all, download the starter file for the app — this contains the finished HTML structure and CSS styling, giving us a game board that shows the two players' information (as seen above), but with the spinner and results paragraph displayed on top of one another. We just have to write the JavaScript code.

    +
  2. +
  3. +

    Inside the empty {{htmlelement("script")}} element on your page, start by adding the following lines of code that define some constants and variables we'll need in the rest of the code:

    + +
    const spinner = document.querySelector('.spinner p');
    +const spinnerContainer = document.querySelector('.spinner');
    +let rotateCount = 0;
    +let startTime = null;
    +let rAF;
    +const btn = document.querySelector('button');
    +const result = document.querySelector('.result');
    + +

    In order, these are:

    + +
      +
    1. A reference to our spinner, so we can animate it.
    2. +
    3. A reference to the {{htmlelement("div")}} element that contains the spinner, used for showing and hiding it.
    4. +
    5. A rotate count — how much we want to show the spinner rotated on each frame of the animation.
    6. +
    7. A null start time — will be populated with a start time when the spinner starts spinning.
    8. +
    9. An uninitialized variable to later store the {{domxref("Window.requestAnimationFrame", "requestAnimationFrame()")}} call that animates the spinner.
    10. +
    11. A reference to the Start button.
    12. +
    13. A reference to the results paragraph.
    14. +
    +
  4. +
  5. +

    Next, below the previous lines of code, add the following function. This simply takes two numerical inputs and returns a random number between the two. We'll need this to generate a random timeout interval later on.

    + +
    function random(min,max) {
    +  var num = Math.floor(Math.random()*(max-min)) + min;
    +  return num;
    +}
    +
  6. +
  7. +

    Next add in the draw() function, which animates the spinner. This is exactly the same as the version seen in the simple spinner example we looked at earlier:

    + +
      function draw(timestamp) {
    +    if(!startTime) {
    +     startTime = timestamp;
    +    }
    +
    +    let rotateCount = (timestamp - startTime) / 3;
    +    spinner.style.transform = 'rotate(' + rotateCount + 'deg)';
    +
    +    if(rotateCount > 359) {
    +      rotateCount -= 360;
    +    }
    +
    +    rAF = requestAnimationFrame(draw);
    +  }
    +
  8. +
  9. +

    Now it is time to set up the initial state of the app when the page first loads. Add the following two lines, which simply hide the results paragraph and spinner container using display: none;.

    + +
    result.style.display = 'none';
    +spinnerContainer.style.display = 'none';
    +
  10. +
  11. +

    We'll also define a reset() function, which sets the app back to the original state required to start the game again after it has been played. Add the following at the bottom of your code:

    + +
    function reset() {
    +  btn.style.display = 'block';
    +  result.textContent = '';
    +  result.style.display = 'none';
    +}
    +
  12. +
  13. +

    OK, enough preparation.  Let's make the game playable! Add the following block to your code. The start() function calls draw() to start the spinner spinning and display it in the UI, hides the Start button so we can't mess up the game by starting it multiple times concurrently, and runs a setTimeout() call that runs a setEndgame() function after a random interval between 5 and 10 seconds has passed. We also add an event listener to our button to run the start() function when it is clicked.

    + +
    btn.addEventListener('click', start);
    +
    +function start() {
    +  draw();
    +  spinnerContainer.style.display = 'block';
    +  btn.style.display = 'none';
    +  setTimeout(setEndgame, random(5000,10000));
    +}
    + +
    +

    Note: You'll see that in this example we are calling setTimeout() without storing the return value (so not let myTimeout = setTimeout(functionName, interval)). This works and is fine, as long as you don't need to clear your interval/timeout at any point. If you do, you'll need to save the returned identifier.

    +
    + +

    The net result of the previous code is that when the Start button is pressed, the spinner is shown and the players are made to wait a random amount of time before they are then asked to press their button. This last part is handled by the setEndgame() function, which we should define next.

    +
  14. +
  15. +

    So add the following function to your code next:

    + +
    function setEndgame() {
    +  cancelAnimationFrame(rAF);
    +  spinnerContainer.style.display = 'none';
    +  result.style.display = 'block';
    +  result.textContent = 'PLAYERS GO!!';
    +
    +  document.addEventListener('keydown', keyHandler);
    +
    +  function keyHandler(e) {
    +    console.log(e.key);
    +    if(e.key === 'a') {
    +      result.textContent = 'Player 1 won!!';
    +    } else if(e.key === 'l') {
    +      result.textContent = 'Player 2 won!!';
    +    }
    +
    +    document.removeEventListener('keydown', keyHandler);
    +    setTimeout(reset, 5000);
    +  };
    +}
    + +

    Stepping through this:

    + +
      +
    1. First we cancel the spinner animation with {{domxref("window.cancelAnimationFrame", "cancelAnimationFrame()")}} (it is always good to clean up unneeded processes), and hide the spinner container.
    2. +
    3. Next we display the results paragraph and set its text content to "PLAYERS GO!!" to signal to the players that they can now press their button to win.
    4. +
    5. We then attach a keydown event listener to our document — when any button is pressed down, the keyHandler() function is run.
    6. +
    7. Inside keyHandler(), we include the event object as a parameter (represented by e) — its {{domxref("KeyboardEvent.key", "key")}} property contains the key that was just pressed, and we can use this to respond to specific key presses with specific actions.
    8. +
    9. We first log e.key to the console, which is a useful way of finding out the key value of different keys you are pressing.
    10. +
    11. When e.key is "a", we display a message to say that Player 1 won, and when e.key is "l", we display a message to say Player 2 won. Note that this will only work with lowercase a and l — if an uppercase A or L is submitted (the key plus Shift), it is counted as a different key.
    12. +
    13. Regardless of which one of the player control keys was pressed, we remove the keydown event listener using {{domxref("EventTarget.removeEventListener", "removeEventListener()")}} so that once the winning press has happened, no more keyboard input is possible to mess up the final game result. We also use setTimeout() to call reset() after 5 seconds — as we explained earlier, this function resets the game back to its original state so that a new game can be started.
    14. +
    +
  16. +
+ +

That's it, you're all done.

+ +
+

Note: If you get stuck, check out our version of the reaction game (see the source code also).

+
+ +

Conclusion

+ +

So that's it — all the essentials of async loops and intervals covered in one article. You'll find these methods useful in a lot of situations, but take care not to overuse them — since these still run on the main thread, heavy and intensive callbacks (especially those that manipulate the DOM) can really slow down a page if you're not careful.

+ +

{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Introducing", "Learn/JavaScript/Asynchronous/Promises", "Learn/JavaScript/Asynchronous")}}

+ + +

במודול זה

+ + diff --git a/files/he/learn/javascript/building_blocks/build_your_own_function/index.html b/files/he/learn/javascript/building_blocks/build_your_own_function/index.html new file mode 100644 index 0000000000..47df4e6b3a --- /dev/null +++ b/files/he/learn/javascript/building_blocks/build_your_own_function/index.html @@ -0,0 +1,247 @@ +--- +title: בניית פונקציה משלנו +slug: Learn/JavaScript/Building_blocks/Build_your_own_function +translation_of: Learn/JavaScript/Building_blocks/Build_your_own_function +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Functions","Learn/JavaScript/Building_blocks/Return_values", "Learn/JavaScript/Building_blocks")}}
+ +

לאחר שסיימנו את רוב התיאוריה במאמר הקודם, מאמר זה נועד להעניק לכם ניסיון מעשי. אנחנו ננסה להעניק לכם כלים לבנות את הפונקציה שלכם. במהלך הדרך, אנחנו נסביר כמה פרטים שימושיים בקשר לשימוש בפונקציות.

+ + + + + + + + + + + + +
ידע מוקדם:הכרות בסיסית עם המחשב ועם הבסיס של HTML ו- CSS, וכן סיום במלאו של מודול צעדים ראשונים ב-JavaScript., Functions — פונקציות - חלקי קוד לשימוש חוזר.
מטרה:לספק לכם כלים לבניית פונקציות ולהסביר פרטים שימושיים בהקשר של בניית פונקציות.
+ +

למידה עצמאית: בניית פונקציה

+ +

הפונקציה שנראה לבנות תיקרא displayMessage(). היא תציג הודעה על גבי דף אינטרנט, אשר תחליף את הפונקציה המובנית של הדפדפן alert(). ראינו משהו דומה לפני כן,על מנת לרענן את הזכרון, הדפיסו את הקוד הבא בקונסולה

+ +
alert('This is a message');
+ +

הפונקציה alert מקבל פרמטר אחד כארגומנט - המחרוזת ששתוצג על גבי תיבת ההודעה. נא לשנות המחרוזת על מנת לשנות את ההודעהf

+ +

הפונקציה alert היא מוגבלת: אנחנו יכולים לשנות את הטקסט, אבל אנחנו לא ממש יכולים לשנות בקלות את כל היתר כמו צבעים, אייקון, או כל דבר אחר. אנו נבנבה פונקציה שתאפשר לנו את הדברים הללו.

+ +
+

לתשומת לב דוגמא זו אמורה לעבוד בכל הדפדפדנים המודרניים, אבל העיצוב עלול להיראות קצת מוזר בדפדפנים ישנים. אנחנו ממליצים ללכם להתשמשמ בדפדפן מודרני כגון פיירפוקס, כרום או אופרה לשם תרגול זה.

+
+ +

הפונקציה הבסיסית

+ +

על מנת להתחיל, בואו נבנה פונקציה בסיסית

+ +
+

לתשומת לב: הכללים בנושא מתן שמות לפונקציה הם דומים לכללים בנושא מתן שמות למשתנים. יחד עם זאת, בפונקציות, לאחר השם יבואו סוגריים רגילות () ואילו במשתנים לא.

+
+ +
    +
  1. התחילו בכך שתיצרו עותק מקומי של הקובץ function-start.html. בקובץ אתם תיראו שה-body כולל כפתור אחד. בנוסף הוספנו גם כמה כללי css פשוטים על מנת לעצב את תיבת ההודעה שלנו וכן אלממנט {{htmlelement("script")}} ריקה שבה נוסיף את קוד ה-JavaScriipt שלנו.
  2. +
  3. לאחר מכן, הוסיפו הקוד הבא בתוך האלמנט <script>: +
    function displayMessage() {
    +
    +}
    + אנחנו מתחילים עם המילה השמורה function, אשר משמעותה היא שאנחנו מגדירים פונקציה. לאחר מכן, אנחנו רושמים את שם הפונקציה שנרצה לתת לה, ולאחר מכן סוגריים רגילות () ולאחריהן סוגריים מסולסלות {....}. הפרמטרים שנרצה לתת לפונקציה שלנו - הארגומנטים, ייכנסו בתוך הסוגריים הרגילות (ובמידה שיש לנו כמה ארגומנטים, נפריד ביניהם באמצעות פסיק , ורווח.) את הקוד שנרצה שהפונקציה תריץ בכל פעם שנקרא לה אנחנו נשים בתוך הסוגריים המסולסות {....}.
  4. +
  5. לבסוף, הוסיפו את התקוד הבא בתוך הסוגריים המסולסלות +
    var html = document.querySelector('html');
    +
    +var panel = document.createElement('div');
    +panel.setAttribute('class', 'msgBox');
    +html.appendChild(panel);
    +
    +var msg = document.createElement('p');
    +msg.textContent = 'This is a message box';
    +panel.appendChild(msg);
    +
    +var closeBtn = document.createElement('button');
    +closeBtn.textContent = 'x';
    +panel.appendChild(closeBtn);
    +
    +closeBtn.onclick = function() {
    +  panel.parentNode.removeChild(panel);
    +}
    +
  6. +
+ +

נעבור על הקוד שהוספנו שורה אחר שורה

+ +

השורה הראשונה משתמשת בפונקציה של DOM API הנקראת {{domxref("document.querySelector()")}}, על מנת לבחור אלמנט מסוג {{htmlelement("html")}} ולאחסן הפנייה אליו בתוך משתנה שנקרא html, כדי שנוכל לבצע איתו דברים מאוחר יותר:

+ +
var html = document.querySelector('html');
+ +

החלק הבא בקוד שלנו משתמש בפונקציה נוספת של DOM API הנקראת {{domxref("document.createElement()")}} על מנת ליצור אלמנט מסוג {{htmlelement("div")}} ואנו מאחסנים הפניה אליו בתוך המשתנה שנקרא panel. האלמנט הזה יהיה הקונטיינר החיצוני של תיבת ההודעה שלנו.

+ +

לאחר מכן אנחנו משתמשים בפונקציה נוספת של DOM API שנקראת class על מנת לקבוע {{domxref("Element.setAttribute()")}} למשתנה msgBox שלנו עם הערך msgBox. זה אמור להקל עלינו לעצב את האלמנט - אם תסתכלו ב-CSS שבדךף, אתם תראו שאנחנו משתשמים בסלקטור של CSS .msgBox על מנת לעצב את תיבת ההודעה והתוכן שלה.

+ +

לבסוף - אנחנו קוראים לפונקציית DOM נוספת שנקראת {{domxref("Node.appendChild()")}} על גבי המשתנה html , אשר משרשרת את האלמנט שהיא מקבלת כארגומנט לאלמנט שהיא הופעלה עליו. כאן אנחנו מציינים שאנחנו רוצים שהאלמנט <div> יהיה אלמנט ילד של האלמנט <html>. אחנו צריכים להוסיף פונקציה זו בכל פעם שאנחנו משתמשים בפונקציה {{domxref("document.createElement()")}}, מכיוון שהאלמנט שיצרנו לא יופיע בעצמו ולא יתחבר בעצמו לאלמנט אחר - אנחנו צריכים לציין איפה אנחנו רוצים לשים אותו ולמי הוא יהיה קשור.

+ +
var panel = document.createElement('div');
+panel.setAttribute('class', 'msgBox');
+html.appendChild(panel);
+ +

ב-2 החלקים הבאים אנחנו עושים שימוש באותן פונקציות createElement() ן- appendChild() שהשתמשנו בהן על מנת ליצור שני אלמנטים חדשים: {{htmlelement("p")}} ו- {{htmlelement("button")}} — ומכניסים אותם בתוך הדף כאלמנטים ילדים של <div> panel. לאחר מכן אנחנו משתמשים בפרופ׳ {{domxref("Node.textContent")}} - אשר מייצג בעצם את תוכן הטקסט של אלמנט - על מנת להכניס הודעה בתוך הפסקה וכן אנחנו מוסיפים את התו 'x' בתוך הכפתור. הכפתור הזה צריך להיות לחוץ/מופעל כשהמשתמש רוצה לסגור את תיבת ההודעה.

+ +
var msg = document.createElement('p');
+msg.textContent = 'This is a message box';
+panel.appendChild(msg);
+
+var closeBtn = document.createElement('button');
+closeBtn.textContent = 'x';
+panel.appendChild(closeBtn);
+ +

לבסוף, אנחנו משתמשים במאזין אירוע ומטפל אירוע - {{domxref("GlobalEventHandlers.onclick")}} - על מנת להוסיף האזנה להתרחשות אירוע של לחיצה (במקרה הזה לחיצה על ) closeBtn וטיפול באותו אירוע על ידי הפונקציה האנונימית המכילה קוד שמוחק את כל ה-panel מהדף - כלומר מוחק את תיבת ההודעה.

+ +

בקצרה, מאזין האירוע onclick הוא פרופ׳ שזמין עבור כפתור (ובעצם זמין עבור כל אלמנט בדף) שיכול להיות מוגדר לפונקציה שתבצע קוד מסויים כאשר הכפתור/האלמנט נלחץ. אנחנו נלמד על כך לעומק במאמר שלנו בנושא אירועים. שימו לב שוב שמטפל האירוע של מאזין האירוע onclick שווה לפונקציה אנונימית, אשר מכילה קוד שירוץ כאשר הכפתור נלחץ. שורת הקוד שבתוך הפונקציה האנונימית משתמש בפונקציה של ה- DOM API בשם {{domxref("Node.removeChild()")}} על מנת להסיר אלמנט בן של אלמנט - במקרה זה של אלמנט <div>.

+ +
closeBtn.onclick = function() {
+  panel.parentNode.removeChild(panel);
+}
+ +

בעיקרון - כל הקוד הזה פשוט יוצר בלוק של HTML שנראה כך ומכניס את זה לתוך הדף:

+ +
<div class="msgBox">
+  <p>This is a message box</p>
+  <button>x</button>
+</div>
+ +

זה היה הרבה קוד לעבור עליו - אל תדאגו אם אתם לא זוכרים במדויק איך הוא עובד כרגע. הרעיון המרכזי שאנחנו רוצים לשים עליו דגש כאן הוא הפונקציה, המבנה שלה והשימוש שלה.

+ +

קריאה לפונקציה/הפעלת הפונקציה

+ +

כעת יש לנו את הגדרת הפונקציה בתוך האלמנט 555555, אבל היא לא תבצע כלום אם לא נקרא לה.

+ +
    +
  1. נסו לכלול את הקוד הבא מחת לפונקציה על מנת לקרוא לה: +
    displayMessage();
    + שורה זו בעצם קוראת פונקציה (Invoking the function) וגורמת לה לרוץ מיד. כאשר תשמרו את הקוד ותעלו מחדש את הדף בדפדפן, אתם תראו שתיבת ההודעה הופיע מיד, פעם אחת. אחרי הכל, קראנו לפונקציה רק פעם אחת.
  2. +
  3. +

    כעת, פתחו את הקונסולה והדפיסו את השורה למעלה שוב, ואתם תראו את ההודעה שוב. כלומר בנינו פונקציה שאנחנו יכולים להשתמש בה שוב ושוב.

    + +

    רוב הסיכויים שנרצה שתיבת ההודעה תופיע כתגובה לאירועים מסויימים של המערכת או של המשתמש. ביישומים אמיתיים, תיבת הודעה שכזו תיקרא בתגובה למידע חדש שזמין או לשגיאה שנוצרה, או כאשר המשתמש מוחק את הפרופיל שלו (״האם אתה בטוח רוצה למחוק את הפרופיל? וכד׳).

    + +

    בתרגול זה, אנחנו נגרום לתיבת ההודעה להופיע כאשר המשתמש לוחץ על כפתור.

    +
  4. +
  5. מחקו את השורה שהוספתם.
  6. +
  7. כעת, אנחנו נבחר את הכפתור ונאחסן הפניה אליו בתוך משתנה. הוסיפו את הקוד הבא לקוד שלהם, מעל הגדרת הפונקציה : +
    var btn = document.querySelector('button');
    +
  8. +
  9. לבסו, הוסיפו את הקוד הבא, מתחת לקוד שהוספתם בסעיף הקודם: +
    btn.onclick = displayMessage;
    + בדרך דומה ל ...closeBtn.onclick בתוך הפונקציה, כאן אנחנו קוראים קוד מסויים בתגובה כך שהכפתור נלחץ. אבל במקרה הזה במקום לקרוא לפונקציה אנונימית המכילה את אותו קוד, אנחנו קוראים לפונקציה שלנו בשמה באופן מפורש.
  10. +
  11. נסו לשמור ולרענן את הדף - אתם אמורים לראות את תיבת ההודעה כאשר הכפתור נלחץ.
  12. +
+ +

אתם בטח תוהים מדוע לא כללנו סוגריים () אחרי שם הפונקציה. הסיבה היא שאנחנו לא רוצים לקרוא לפונקציה ישר - אלא רק אחרי שהכפתור נלחץ. אם תשנו את השורה הבא כך:

+ +
btn.onclick = displayMessage();
+ +

ותרעננו את הדף, אתם תיראו שהתיבת ההודעה הופיע מבלי שלחצנו על הכפתור. הסוגריים () בהקשר זה לפעמים נקראים "function invocation operator". אנחנו משתמשים בהם כאשר אנחנו רוצים להריץ את הפונקציה באופן מיידי בתוך הסקופ הנוכחי. באותו דרך, הקוד שבתוך הפונקציה האנונימית לא ירוץ ישר, שכן הוא נמצא בתוך הסקופ של הפונקציה בלבד - שכאמור תופעל רק כאשר כפתור יילחץ.

+ +

אם ניסיתם את התרגול הקודם של הוספת (), אנא וודאו שמחקתם אותם לפני שאתם ממשיכים

+ +

שדרוג הפונקציה שלנו באמצעות פרמטרים/ארגומנטים

+ +

כרגע, הפונקציה שלנו לא ממש שימושית - אנחנו לא רוצים סתם להציג הודעה זהה בכל פעם. ננסה לשדרג אוהת על ידי כך שנוסיף מספר פרמטרים, אשר יאפשרו לנו לקרוא לה, אך עם אפשרויות שונות בכל קריאה.

+ +
    +
  1. תחילה, עדכנו את השורה הראשונה של הפונקציה: +
    function displayMessage() {
    + +
    לקוד הבא:
    + +
    function displayMessage(msgText, msgType) {
    + כעת, כאשר אנחנו קוראים לפונקציה, אנחנו מספקים לה שני ערכים של משתנים בתוך הסוגריים () על מנת לציין את תוכן ההודעה שתוצג ואת סוג ההודעה.
  2. +
  3. על מנת לעשות שימוש בפרמטר הראשון, עדכנו את הקוד שבתוך הפונקציה : +
    msg.textContent = 'This is a message box';
    + +
    לקוד הבא
    + +
    msg.textContent = msgText;
    +
  4. +
  5. לבסוף, אנחנו נרצה לעדכן כעת את הפונקציה כך שתכלול הודעה מעודכנת . שנה את השורה הבאה: +
    btn.onclick = displayMessage;
    + +
    לקוד הבא :
    + +
    btn.onclick = function() {
    +  displayMessage('Woo, this is a different message!');
    +};
    + If we want to specify parameters inside parentheses for the function we are calling, then we can't call it directly — we need to put it inside an anonymous function so that it isn't in the immediate scope and therefore isn't called immediately. Now it will not be called until the button is clicked.
  6. +
  7. עכשיו טען מחדש ונסה שוב את הקוד ותראה שהוא עדיין עובד כמו מקודם ,רק שעכשיו גם התווסף אפשרות לשנות את ההודעה שבתוך הפרמטר כדי להציג הודעות שונות בתיבה! 
  8. +
+ +

פרמטר מורכב יותר

+ +

הלאה לפרמטר הבא. זו תכלול עבודה מעט יותר - אנו מתכוונים להגדיר אותה כך שלפי הפרמטר msgType, הפונקציה תציג אייקון אחר וצבע רקע שונה.

+ +
    +
  1. First of all, download the icons needed for this exercise (warning and chat) from GitHub. Save them in a new folder called icons in the same location as your HTML file. + +
    Note: The warning and chat icons were originally found on iconfinder.com, and designed by Nazarrudin Ansyari — Thanks! (The actual icon pages were since moved or removed.)
    +
  2. +
  3. Next, find the CSS inside your HTML file. We'll make a few changes to make way for the icons. First, update the .msgBox width from: +
    width: 200px;
    + +
    ל
    + +
    width: 242px;
    +
  4. +
  5. Next, add the following lines inside the .msgBox p { ... } rule: +
    padding-left: 82px;
    +background-position: 25px center;
    +background-repeat: no-repeat;
    +
  6. +
  7. Now we need to add code to our displayMessage() function to handle displaying the icons. Add the following block just above the closing curly brace (}) of your function: +
    if (msgType === 'warning') {
    +  msg.style.backgroundImage = 'url(icons/warning.png)';
    +  panel.style.backgroundColor = 'red';
    +} else if (msgType === 'chat') {
    +  msg.style.backgroundImage = 'url(icons/chat.png)';
    +  panel.style.backgroundColor = 'aqua';
    +} else {
    +  msg.style.paddingLeft = '20px';
    +}
    + Here, if the msgType parameter is set as 'warning', the warning icon is displayed and the panel's background color is set to red. If it is set to 'chat', the chat icon is displayed and the panel's background color is set to aqua blue. If the msgType parameter is not set at all (or to something different), then the else { ... } part of the code comes into play, and the paragraph is simply given default padding and no icon, with no background panel color set either. This provides a default state if no msgType parameter is provided, meaning that it is an optional parameter!
  8. +
  9. Let's test out our updated function, try updating the displayMessage() call from this: +
    displayMessage('Woo, this is a different message!');
    + +
    to one of these:
    + +
    displayMessage('Your inbox is almost full — delete some mails', 'warning');
    +displayMessage('Brian: Hi there, how are you today?','chat');
    + You can see how useful our (now not so) little function is becoming.
  10. +
+ +
+

לתשומת לב: אם אתם נתקלים בבעיות או הדוגמא אינה עובדת לכם, אנא בדקו את הקוד שלכם אל מול הקוד הסופי שלנו ב- GitHub (או בדף האינטרנט או שאלו אותנו

+
+ +

לסיכום

+ +

במאמר זה ניסינו להסביר לכם את התהליך של בניית פונקציה בעצמנו, כאשר עם עט עבודה נוספת, יכול להפוך לפרוייקט אמיתי. במאמר הבא אנחנו נסיים לעבור על נושא פונקציות ונסביר עקרון חשוב נוסף בנושא זה - ערכי החזרה — return values.

+ + + +

{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Functions","Learn/JavaScript/Building_blocks/Return_values", "Learn/JavaScript/Building_blocks")}}

+ +

במודול זה

+ + diff --git a/files/he/learn/javascript/building_blocks/events/index.html b/files/he/learn/javascript/building_blocks/events/index.html new file mode 100644 index 0000000000..9fc4363939 --- /dev/null +++ b/files/he/learn/javascript/building_blocks/events/index.html @@ -0,0 +1,588 @@ +--- +title: היכרות ראשונית עם אירועים - Events +slug: Learn/JavaScript/Building_blocks/Events +translation_of: Learn/JavaScript/Building_blocks/Events +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Return_values","Learn/JavaScript/Building_blocks/Image_gallery", "Learn/JavaScript/Building_blocks")}}
+ +

אירועים (Evants) אלו פעולות או התרחשויות אשר קורות במערכת שאנחנו מתכנתים בה, והמערכת אומרת לנו  בדרך מסויימת על ההתרחשות שלהם, כך שאנחנו יכולים להגיב להתרחשות של האירוע המסויים בדרך מסויימת שנרצה. לדוגמא אם משתמש לחץ על כפתור באתר, אולי נרצה בתגובה לטפל באירוע הלחיצה הזה על ידי הצגת הודעה כלשהי. במאמר זה אנחנו נדון בעקרונות החשובים של events ונסתכל כיצד הם עובדים בדפדפדנים. אנחנו לא נרחיב יותר מדי, אלא רק מה שתצטרכו לדעת בשלב זה.

+ + + + + + + + + + + + +
ידע מוקדם:הכרות בסיסית עם המחשב ועם הבסיס של HTML ו- CSS, וכן סיום במלאו של מודול צעדים ראשונים ב-JavaScript.
מטרה:להבין את התיאוריה הבסיסית של אירועים וכיצד הם עובדים בדפדפנים וכיצד אירועים יכולים להיות שונים בסביבות פיתוח שונות.
+ +

מה הם אירועים? 

+ +

כפי שרשמנו למעלה, אירועים, events, הם פעולות או התרחשויות שקורות במערכת שאנחחנו מתכנתים עליה - המערכת שולחת סימן מסויים שהאירוע מתרחש וגם מספקת לנו מכניזם מסויים שעל פיו כלומר, קוד מסויים ירוץ בתגובה להתרחשות אירוע מסויים. כמו בדוגמא עם לחיצת הכפתור שפירטנו למעלה. כאשר האירוע של ״לחיצת כפתור״ התרחש, הדפדפן שלח לנו סימן מסויים שהתרחש אירוע וטיפלנו בו באמצעות הקפצת חלונית.

+ +

במקרה שלנו, אירועים מתרחשים בתוך חלון הדפדפן, ונוטים להיות מחוברים לפריט מסויים שבו הם התרחשו או עליו הם קרו - זה יכול להית אלמנט אחד, מספר אלמנטים, אירוע של טעינה דף HTML בלשונית מסויימת או טעינתו של חלון הדפדפן כולו.

+ +

יש הרבה סוגים של אירועים שיכולים להתרחש. הנה דוגמא קטנה שלהם:

+ + + +

תוכלו לראות בדף MDN בנושא Event reference שיש לא מעט סוגי אירועים שניתן לטפל בהם - כלומר להגיב להתרחשותם.

+ +

לכל אירוע זמין יש ״מטפל אירוע״ - event handler, שזה בעצם בלוק של קוד שבדרך כלל זו פונקציה שאנחנו נגדיר בעצמנו ושירוצו כאשר האירוע החל להתרחש. שימו לב שלפעמים event handlers נקראים event listeners - ״מאזיני אירוע״ בעיקרון, הם כמעט אותו דבר מבחינתנו כרגע, אבל יש הבדלים ביניהם, הם עובדים יחד: מאזין אירוע - event listeners - מאזין להתרחשות האירוע, ואילו מטפל האירוע - event handlers, מטפל באותו אירוע שהתרחש - (הקוד שמורץ בתגובה להתרחשות של אותו אירוע).

+ +
+

לתשומת לב: חשוב לדעת כי אירועי web אינם חלק מהבסיס של JavaScript - הם מוגדרים כחלק מה-API של JavaScript המובנים בתוך הדפדפן.

+
+ +

דוגמא

+ +

נסתכל על דוגמא פשוטה על מנת להסביר את הנושא. ראינו כבר אירועים ו-event handlers בהרבה מהדוגמאות במהלך הקורס אבל בואו נרענן את הזיכרון.

+ +

הסתכלו בדוגמא הבאה, יש לנו אלמנט {{htmlelement("button")}} אחד, אשר כאשר הוא נלחץ, הוא שנה את הצבע של הרקע לצבע אקראי:

+ +
<button>Change color</button>
+ + + +

קוד ה-JavaScript שלנו נראה כך:

+ +
var btn = document.querySelector('button');
+
+function random(number) {
+  return Math.floor(Math.random()*(number+1));
+}
+
+btn.onclick = function() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+ +

בדוגמא למעלה, אחסנו הפניה לאלמנט <button> בתוך משתנה שנקרא btn, באמצעות פונקציית {{domxref("Document.querySelector()")}}. בנוסף ,הגדרנו פונקציה שמחזירה לנו מספר אקראי. החלק השלישי של הקוד הוא מטפל האירוע - event handler. המשתנה btn מצביע על אלמנט  <button> ולסוג הזה של האובייקט יש מספר מסוים של אירועים שיכולים להתרחש עליו, ולכן יש מספר מטפלי אירוע זמינים עבורו.

+ +

בדוגמא זו אנחנו מקשיבים בעצם לאירוע/התרחשות של לחיצת עכבר באמצעות השמת ערך לתכונה (property) של event handler השווה לפונקציה אנונימית. פונקציה אנונימית זו מכילה קוד שמייצר צבע רנדומלי בפורמט rgb וקובעת את ה-background-color לצבע זה.

+ +

הקוד שבפונקציה האנונימית ירוץ בכל פעם שאירוע הלחיצה על האלמנט <button> יתרחש, כלומר בכל פעם שהמשתמש לחץ על האלמנט הזה.

+ +

התוצאה של הדוגמא תהא כך:

+ +

{{ EmbedLiveSample('A_simple_example', '100%', 200, "", "", "hide-codepen-jsfiddle") }}

+ +

זה לא רק בדפי האינטרנט

+ +

דבר נוסף שנרצה להזכיר בנקודה זו הוא שאירועים הם לא מיוחדים ל-JavaScript - רוב שפות התכנות מכילות מודל כלשהו של אירועים, והדרך שבה מודל זה עובד בהם, יהיה לרוב שונה מהדרך שבה מודל זה עובד ב-JavaScript. האמת, מודל האירועים ב-JavaScript עבור דפי אינטרנט, שונה ממודל האירועים עבור JavaScript כאשר היא בסביבות אחרות.

+ +

לדוגמא, Node.js היא סביבה המאפשרת לנו הרצה ושימוש ב-JavaScript בצד השרת. מודל האירועים של Node.js מתבסס על מאזינים (listeners) אשר מאזינים לאירועים ועל פולטים (emitters) אשר פולטים אירועים בתדירות מסויימת - זה לא נשמע שונה, אבל הקוד הוא שונה, ושם מתבצע שימוש בפונקציות כמו ()on על מנת לרשום מאזין אירוע ו-()once על מנת לרשום מאזין אירוע שיאזין באופן חד פעמי ויתבטל לאחר שהורץ פעם אחת. דוגמא לכך ניתן לראות ב-HTTP connect event docs.

+ +

דוגמא נוספת למודל אירועים שונים אנחנו יכולים לראות כאשר משתמשים ב-JavaScript על מנת לבנות תוספים לדפדפנים (מעין שיפורים לדפדפנים) - באמצעות טכנולוגיה שנקראת WebExtensions. מודל האירועים שם הוא דומה למודל האירועים של ה-Web, אבל שונה מעט - מאזיני האירועים הם camel-cased - כלומר, onMessage ולא onmessage, והם צריכים להיות ביחד עם פונקצית addListener. לדוגמאות ראו runtime.onMessage page.

+ +

אינכם צריכים להבין עכשיו שום דבר על הסביבות הללו, רק רצינו להסביר לכם שאירועים ומודל האירועים יכול להיות בסביבות פיתוח שונות.

+ +

דרכים לשימוש ב-web events

+ +

יש מספר דרכים שונות שבהם אנחנו יכולים להוסיף מאזין אירוע -event listener לדפי הרשת על מנת שהוא יריץ את ה-event handler כאשר יתרחש האירוע הרלוונטי (event registration). בחלק זה, אנחנו נסקור את הדרכים השונות ונדון באילו מהן אנו צריכים להשתמש.

+ +

דרך I: הוספת תכונה של מטפל אירוע - Event handler properties

+ +

דרך אחת היא בעצם לתת לאלמנט מסויים תכונה של מאזין אירוע והערך שלה יהיה מטפל אירוע. אנו נקרא לה ״תכונת מטפל אירוע״. נתקלנו בזה במהלך הקורס לא מעט. אם נחזור לדוגמא למעלה:

+ +
var btn = document.querySelector('button');
+
+btn.onclick = function() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+ +

התכונה onclick היא תכונת מטפל האירוע (מאזין האירוע) הרלוונטית כרגע לדוגמא זו. היא תכונה בדיוק כמו שיש ל-btn תכונות נוספות שזמינו תעבורו כמו btn.textContent, או btn.style, אבל היא תכונה מסוג מיוחד - כאשר אנחנו משימים בה ערך ששווה לקוד מסויים, הקוד הזה ירוץ בכל פעם שהאירוע יתרחש על הכפתור (או על האלמנט אשר נתנו לו את התכונה הזו).

+ +

אנחנו גם יכולים לתת למטפל אירוע שכזה שיהיה שווה לשם של פונקציה מסויימת, כמו שראינו במאמר בניית פונקציות משלנו. הקוד הבא יעבוד בצורה מצויינת:

+ +
var btn = document.querySelector('button');
+
+function bgChange() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+
+btn.onclick = bgChange;
+ +

יש הרבה סוגים של תכונות מטפלות אירוע שזמינות. ננסה כמה מהם:

+ +

ראשית, שמרו לכם עותק מקומי של random-color-eventhandlerproperty.html, ופיתחו אותו בדפדפן. זהו עותק של הדוגמא הפשוטה של בחירת הצבע שראינו בעבר. עכשיו שנו את ה- btn.onclick לערכים הבאים, כל אחד בתור, וראו מה קורה :

+ + + +

ישנם אירועים שהם מאד כלליים והם זמינים כמעט בכל מקום או עבור כל אלמנט - לדוגמא - אפשר להאזין לאירוע onclick כמעט על כל אלמנט, בעוד יש כאלו שהם יותר ספציפיים ושימושיים בסיטואציות מסויימת. לדוגמא, הגיוני לנו ש-onplay יהיה זמין רק לאלמנטים מסוג מסויים כמו {{htmlelement("video")}}.

+ +

דרך II: לידיעה בלבד - לא להשתמש בהם - Inline event handlers

+ +

יכול להיות שראיתם קוד שנראה כך:

+ +
<button onclick="bgChange()">Press me</button>
+
+ +
function bgChange() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+ +
+

לתשומת לב: אתם יכולים לראות את קוד המקור לדוגמא זו ב- GitHub או בדף אינטרנט.

+
+ +

בעבר, הדרך לרשום (register) מטפלי אירוע הייתה באמצעות event handler HTML attributes הידועים גם כ- inline event handlers, כמו שרשום בדוגמא למעלה. הערך של אותו attribute הוא ממש קוד JavaScript שאנחנו רוצים שירוץ כאשר האירוע מתרחש. הדוגמא למעלה מפעילה פונקציה שמוגדרת בתוך האלמנט {{htmlelement("script")}} אבל באותה הדרך אנחנו יכולים להכניס פונקציה שלמה לתוך אותו attribute:

+ +
<button onclick="alert('Hello, this is my old-fashioned event handler!');">Press me</button>
+ +

אל תשתמשו בדרך שכזו על מנת לטפל באירוע, זה נחשב כ- bad practice (פרקטיקה שאינה מקובלת בתעשייה). זה אולי נשמע יותר פשוט, אבל מהר מאוד זה הופך למשהו שלא ניתן לעקוב אחריו ולא יעיל.

+ +

בנוסף, זה לא רעיון טוב לערבב בין HTML לבין JavaScript מאחר שזה נהיה קשה לעיבוד - היצמדו לכך שכל ה-JavaScript נמצא במקום אחד.

+ +

אפילו כאשר מדובר בקובץ אחד, inline event handlers הם לא רעיון טוב. כאשר יש כפתור אחד זה עוד סביר, אבל מה אם היו לנו 100 כפתורים? היינו צריכים להוסיף 100 attributes לתוך הקובץ. מהר מאוד זה הופך לסיוט מבחינת תחזוקה של הקוד. עם JavaScript, אנחנו יכולים בקלות להוסיף מטפל אירוע לכל הכפתורים, לא משנה כמה יש כאלו, באמצעות קוד כזה:

+ +
var buttons = document.querySelectorAll('button');
+
+for (var i = 0; i < buttons.length; i++) {
+  buttons[i].onclick = bgChange;
+}
+ +
+

לתשומת לב: הפרדה בין הקוד שלנו לבין התוכן גם הופך את האתר שלנו ליותר ידידותי למנועי החיפוש.

+
+ +

דרך addEventListener() : III  ו- ()removeEventListener

+ +

הסוג החדש ביותר של מנגנון אירועים הוגדר ב- Document Object Model (DOM) Level 2 Events של ארגון W3C. מסמך זה הגדיר דרך טובה יותר לנהל אירועים, בין היתר באמצעות אובייקט מיוחד בשם  EvantTarget אשר נוצר בדפדפן כאשר אירוע מתרחש. לאובייקט זה יש שלוש מתודות ואחת מהן היא ()addEventListener. מתודה זו דומה לדרך הראשונה של event handler properties, אבל הסינטקס שונה. אנחנו יכולים לכתוב את הדוגמא שלנו עם הצבעים האקראיים בצורה הזו:

+ +
var btn = document.querySelector('button');
+
+function bgChange() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+
+btn.addEventListener('click', bgChange);
+ +
+

לתשומת לב:תוכלו למצוא את קוד המקור של דוגמא זו ב- GitHub או ראו כ- דף אינטרנט).

+
+ +

בתוך מתודת ()addEventListener, אנחנו מציינים שני פרמטרים - אחד בעבור אותו האירוע, אותו ה-event אשר אנחנו רוצים שיאזינו והפרמטר השני זה פונקציה של הקוד שאנחנו רוצים שירוץ כמטפל באותו אירוע. שימו לב שזה בסדר גמור לשים את כל הקוד שיטפל באירוע כפונקציה אנונימית, בשונה מהדוגמא למעלה:

+ +
btn.addEventListener('click', function() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+});
+ +

לשיטה הזו יש יתרונות ברורים על השיטות הישנות שדנו בהם למעלה. ראשית, יש מתודה נוספת בשם ()removeEventListener אשר מאפשרת לנו להסיר מאזיני אירוע. לצורך העניין, הקוד הבא יסיר את מאזין האירוע שקבענו למעלה:

+ +
btn.removeEventListener('click', bgChange);
+ +

זה אמנם לא כזה משמעותי עבור תוכניות קטנות או פשוטות, אבל בעבור תוכניות גדולות או מורכבות, זה יכול להגביר את היעילות ומאפשר לנקות מטפלי אירוע שאינם בשימוש עוד. בנוסף, זה מאפשר לנו שלאותו אלמנט - לאותו הכפתור - יהיו מספר מטפלי אירועים אשר יפעלו בצורה אחרת באירועים שונים - כל מה שאנחנו צריכים לעשות זה להוסיף/להסיר מטפלי אירוע בהתאם.

+ +

בנוסף, אנחנו גם יכולים לרשום מספר מטפלי אירוע לאותו אירוע - הקוד הבא לדוגמא לא יכול להחיל שני מטפלי אירוע:

+ +
myElement.onclick = functionA;
+myElement.onclick = functionB;
+ +

זאת מכיוון שהשורה השנייה דורסת את הערך שנקבע ל-onclick של השורה הראשנה. על מנת להוסיף מטפל אירוע נוסף מבלי לדרוס את מטפל את האירוע הקיים, אנחנו יכולים לעשות משהו כזה:

+ +
myElement.addEventListener('click', functionA);
+myElement.addEventListener('click', functionB);
+ +

במקרה זה, שתי הפונקציות ירוצו כאשר ילחצו על האלמנט.

+ +

כמו כן, יש מספר אפשרויות משמעותיות ותכונות זמינות עבור מנגנון ירועים בדרך הזו. אנחנו לא נרחיב עליהם, אך אם תרצו להרחיב את ידיעתכם בנושא, היכנסו לדפי ההסבר של MDN בנושא ()addEventListener ובנושא ()removeEventListener.

+ +

באיזה מנגנון אירועים להשתמש?

+ +

מתוך שלושת המנגנונים הללו, בוודאות אל תשתמשו במנגנון HTML event handler attributes - זה מנגנון ישן, שלא נמצא כבר בשימוש ונחשב כ- bad practice להשתמש בו.

+ +

השניים האחרים הם יחסית די חלופיים כאשר מדובר בתוכנית פשוטה או כאשר מדובר בשימוש פשוט שנרצה לעשות באירועים:

+ + + +

כמו שאמרנו, היתרון העיקרי של המנגנון השלישי הוא שאתם יכולים להסיר קוד שמטפל באירוע, באמצעות ()removeEventListener, ואתם יכולים להוסיף מספר מאזיני אירוע לאותו אלמנט. לדוגמא, אנחנו יכולים לקרוא ל-({ ... }()addEventListener('click', function על אלמנט מסויים מספר רב של פעמים, כאשר בכל פעם תהיה פונקציה אחרת בארגומנט השני. אופציה זו לא אפשרית ב- event handler properties כי כל הגדרה נוספת של property תמחוק את ההגדרה הקודמת שלו:

+ +
element.onclick = function1;
+element.onclick = function2;
+etc.
+ +
+

לתשומת לב: אם אתם נדרשים לתמוך בדפדפנים ישנים מאינטרנט אקפלורר 8, אתם עלולים להיתקל בקשיים שכן דפדפדנים ישנים אלו משתמשים במודל אירועים שונה מדפדפנים חדשים, אך אל פחד. מרבית ספריות JavaScript (כמו לדוגמא jQuery) מכילות פונקציות מובנות שמבטלות כביכול את ההבדלים בין הדפדנים השונים. אין לכם צורך לדאוג לנושא זה בתחילת הלמידה שלכם.

+
+ +

עקרונות נוספים בנושא אירועים

+ +

בחלק זה, אנחנו נגע בקצרה בנושאים מתקדמים הקשורים לאירועים. אין זה הכרחי להבין נושאים אלו לעומק בשלב זה, אך זה עלול לסייע לכם להבין תבניות קוד שתיתקלו בהם מדי פעם.

+ +

Event objects

+ +

לפעמים בתוך פונקצייה המטפלת באירוע (event handler) - אתם תראו פרמטר המצויין בתך הסוגריים, הנושא שם כמו event, evt, או סתם e. זה נקרא event object - האובייקט של האירוע עצמו, והוא מועבר בצורה אוטומטית למטפלי האירוע על מנת לספק אפשרויות נוספות ומידע נוסף. לדוגמא, נרשום את דוגמת הצבעים שלנו מחדש בצורה קצת שונה:

+ +
function bgChange(e) {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  e.target.style.backgroundColor = rndCol;
+  console.log(e);
+}
+
+btn.addEventListener('click', bgChange);
+ +
+

לתשומת לב: תוכלו למצוא את קוד המקור ב-GitHub וגם לראות את הדוגמא כדף אינטרנט.

+
+ +

כאן אנחנו יכולים לראות שאנחנו כוללים את האובייקט של האירוע - e, בתוך הפונקציה, ובתוך הפונקציה אנחנו קובעים צבע רקע ל- e.target — שזה בעצם הכפתור עצמו. המאפין target של event object הוא תמיד הפנייה לאלמנט שהאירוע התרחש עליו. כך, בדוגמא שלנו, אנחנו קובעים בעצם צבע רקע אקראי לכפתור עצמו שהאירוע הלחיצה התרחש עליו ולא לדף.

+ +
+

לתשומת לב: אתם יכולים להשתמש באיזה שם שנרצה עבור event object — רק השתמשו בשם שיהיה ברור שזה הפניה ל- event object. השמות המקובלים הם e/evt/event מכיוון שהם קצרים וקל לזכור את ההקשר שלהם.

+
+ +

e.target הוא שימושי להפליא כשאנחנו רוצים לקבוע את אותו event handler על מספר אלמנטים ולעשות משהו לכולם כאשר אותו אירוע מתרחש. לדוגמא, נניח ויש לנו סט של 16 אריחים שנעלמים כאשר הם נלחצים. זה נוח יותר כאשר מתאפשר לנו לקבוע שאלמנט יעלם כשאנחנו נלחץ עליו באמצעות שימוש ב- e.target , מאשר לבחור אותו בצורה מורכבת אחרת. בדוגמאות הבאות למשל ב-useful-eventtarget.html - קוד המקור (ניתן לראות גם ב-דף האינטרנט) יצרנו 16 אלמנטים מסוג {{htmlelement("div")}} באמצעות JavaScript, ואנחנו בוחרים את כולם באמצעות {{domxref("document.querySelectorAll()")}} ואז עוברים על כל אחד מהם באמצעות לולאה ומוסיפים מאזין אירוע ומטפל אירוע של onclick לכל אחד מהם כך שכאשר כל אחד מהאלמנטים הללו נלחץ על ידי המשתמש, צבע אקראי אחר ניתן לאותו אלמנט:

+ +
var divs = document.querySelectorAll('div');
+
+for (var i = 0; i < divs.length; i++) {
+  divs[i].onclick = function(e) {
+    e.target.style.backgroundColor = bgChange();
+  }
+}
+ +

הפלט נראה כך. נסו לשחק איתו:

+ + + +

{{ EmbedLiveSample('Hidden_example', '100%', 400, "", "", "hide-codepen-jsfiddle") }}

+ +

הרבה ממאזיני האירועים/מטפלי האירועים שניתקל בהם הם בעלי סט סטנדרטי של properties ופונקציות - או יותר נכון מתודות, אשר זמינים עבור ה-event object - ראו את הדף בנושא אובייקט {{domxref("Event")}} לרשימה המלאה.

+ +

יש מטפלי אירועים יותר מורכבים, המכילים properties מיוחדים בעלי מידע ספציפי שהם צריכים על מנת לתפקד כמטפל אירוע. לדוגמא ל-Media Recorder API, יש סוג אירוע - dataavailable - שמתרחש כאשר אודיו או וידאו הוקלטו והם זמינים כך שניתן לבצע עליהם פעולות מסויימות - לדוגמא לשמור אותם או לנגן אותם שוב. למאזין האירוע/מטפל אירוע התואם ondataavailable יש property שזמין בשם data עבורו המכיל את האודיו/וידאו שהוקלט ומאפשר לנו לגשת אליו ולעשות איתו דברים.

+ +

מניעת התנהגות ברירת מחדל

+ +

לפעמים אנחנו ניתקל בסיטואצית שאנחנו נרצה למנוע מאירוע לבצע את מה שהוא אמור לעשות כברירת מחדל. הדוגמא הכי נפוצה היא טופס באינטרנט. כאשר אנחנו נמלא את הפרטים ונלחץ על כפתור ה-Submit , ההתנהגות ברירת המחדל תהיה לשלוח את המידע שהוכנס בטופס לדף מסויים בשרת לשם עיבוד, והדפדפן יועבר למעין דף של ״הפרטים נשלחו בהצלחה״ או משהו דומה.

+ +

הבעיה מתעוררת כאשר המשתמש לא הזין את המידע כראוי - כמפתחים, אנחנו נרצה למנוע שליחה של המידע השגוי לשרת ולתת למשתמש הודעת שגיאה שאומרת להם מה הייתה הטעות ומה הם צריכים לעשות. חלק מהדפדנים תומכים בולידציה של מידע בטפסים, אך מכיון שהרבה לא ומסיבות נוספות, אנחנו ממליצים לא להסתמך על ולידציה של דפדפנים אלא לבנות את הולידציה בעצמכם. לדוגמא:

+ +

נתחיל עם טופס HTML פשוט דורש מאיתנו להכניס שם פרטי ושם משפחה:

+ +
<form>
+  <div>
+    <label for="fname">First name: </label>
+    <input id="fname" type="text">
+  </div>
+  <div>
+    <label for="lname">Last name: </label>
+    <input id="lname" type="text">
+  </div>
+  <div>
+     <input id="submit" type="submit">
+  </div>
+</form>
+<p></p>
+ + + +

כעת קצת JavaScript - כאן החלנו בדיקה פשוטה מאוד בתוך מטפל האירוע onsubmit (האירוע של submit מתרחש כאשר הטופס נשלח).

+ +

הבדיקה שלנו בודקת הם שדות הטקסט ריקים. אם כן, אנחנו קוראים לפונקציית ()preventDefault על ה- event object - כלומר על האלמנט שעליו התרחש האירוע. פונקצייה זו מונעת מהטופס להישלח - ומציגה הודעת שגיאה בפסקה מתחת לטופס שלנו, על מנת להציג למשתמש מה השתבש:

+ +
var form = document.querySelector('form');
+var fname = document.getElementById('fname');
+var lname = document.getElementById('lname');
+var submit = document.getElementById('submit');
+var para = document.querySelector('p');
+
+form.onsubmit = function(e) {
+  if (fname.value === '' || lname.value === '') {
+    e.preventDefault();
+    para.textContent = 'You need to fill in both names!';
+  }
+}
+ +

ברור שזו ולידציה פשוטה וחלשה מאוד - זה לא ימנע מהמשתמש להזין רווחים או מספרים לתוך שדות הטקסט, אך זה מספיק לשם הדוגמא. הפלט ייראה כך:

+ +

{{ EmbedLiveSample('Preventing_default_behavior', '100%', 140, "", "", "hide-codepen-jsfiddle") }}

+ +
+

לתשומת לב: ראו את קוד המקור פה preventdefault-validation.html או דף אינטרנט.

+
+ +

event bubbling ו- capture

+ +

נושא נוסף שאנחנו נרצה לדון הוא משהו שאמנם לא ניתקל בו הרבה, אך אם לא נכיר אותו ונבין אותו, יכול לעשות לנו כאב ראש לא קטן.

+ +

event bubbling ו- capture אלו שני מנגנונים אשר מסבירים מה קורה כאשר שנים או יותר מטפלי אירוע של אותו אירוע מופעלים על אלמנט אחד. לצורך ההסבר, פתחו את show-video-box.html בלשונית חדשה בדפדפן ואת קוד המקור בלשונית אחרת. ניתן גם לראות את הדוגמא כאן למטה:

+ + + +

{{ EmbedLiveSample('Hidden_video_example', '100%', 500, "", "", "hide-codepen-jsfiddle") }}

+ +

זו דוגמא פשוטה שמראה ומסתירה אלמנט {{htmlelement("div")}} שמכיל אלמנט {{htmlelement("video")}} בתוכו:

+ +
<button>Display video</button>
+
+<div class="hidden">
+  <video>
+    <source src="rabbit320.mp4" type="video/mp4">
+    <source src="rabbit320.webm" type="video/webm">
+    <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
+  </video>
+</div>
+ +

כאשר אנחנו לוחצים על {{htmlelement("button")}} הוידאו מוצג, באמצעות שינוי ה-class של <div> מ- hidden ל- showing (ה-css בקובץ מכיל בין היתר שני classes אשר מציגים את הקופסא במסך או מסתירים אותה, בהתאמה) :

+ +
btn.onclick = function() {
+  videoBox.setAttribute('class', 'showing');
+}
+ +

לאחר מכן אנחנו מוסיפים עוד שני מטפלי אירוע של onclick - הראשון ל- <div> והשני ל - <video>. הרעיון הוא שכאשר האזור של ה- <div> מחוץ לוידאו מקבל לחיצה, הקופסא אמורה להיעלם שוב; כאשר הוידאו עצמו נלחץ, הוידאו אמור לפעול שוב:

+ +
videoBox.onclick = function() {
+  videoBox.setAttribute('class', 'hidden');
+};
+
+video.onclick = function() {
+  video.play();
+};
+ +

אבל ישנה בעי כרגע, כאשר אנחנו לוחצים על הוידאו הוא מתחיל להתנגן, אבל גורם גם ל- <div> להיות מוסתר באותו הזמן. זה מכיוון שהוידאו שבתוך ה-<div> - הוא חלק ממנו - אז כאשר אנחנו לוחצים על הוידאו - אנחנו בעצם גם מפעילים את האירוע על ה-<div> עצמו, ושני מטפלי האירוע נכנסים לפעולה.

+ +

bubbling ו- capturing

+ +

כאשר אירוע מתרחש על אלמנט שיש לו אלמנט אב - לדוגמא האלמנט {{htmlelement("video")}} שלנו, לדפדפנים המודרניים יש שני תהליכים שונים שהם מבצעים: שלב ה- capturing ושלב ה- bubbling.

+ +

בשלב - capturing:

+ + + +

בשלב - bubbling קורה בדיוק ההפך:

+ + + +

+ +

לחצו על התמונה על מנת להגדיל אותה.

+ +

בדפדפנים מודרניים, ברירת המחדל היא שכל ה-event handlers נרשמים בשלב ה-bubbling. בדוגמא שלנו למשל, כאשר לחצנו על הוידאו, האירוע מסוג לחיצה ״בועבע״ מאלמנט <video> הלאה לאלמנט <html>, כאשר במהלך הדרך :

+ + + +

שימו לב שמה שבועבע הוא התרחשות האירוע עצמו, ולא מטפל האירוע (אותו דבר קורה גם בשלב ה-capturing). 

+ +

תיקון הבעיה עם ()stopPropagation

+ +

על מנת לתקן את ההתנהגות הזו, לאובייקט האירוע עצמו - event object - יש מתודה זמינה עבורו שנקראת ()stopPropagation, כאשר היא מופעלת על מטפל האירוע של אובייקט האירוע, היא תריץ את מטפל האירוע, אבל תמנע מהאירוע עצמו להמשיך לבעבע במעלה השרשרת לאלמנטי האב שלו (וכנ״ל גם בשלב ה- capturing) וכך מטפלי אותו אירוע של אלמנטי האב לא ירוצו.

+ +

כך, על מנת לתקן את הבעיה בדוגמא שלנו, אנחנו נשנה את הפונקציה המטפלת באירוע כך:

+ +
video.onclick = function(e) {
+  e.stopPropagation();
+  video.play();
+};
+ +

אתם יכולים ליצור עותק מקומי של קוד המקור של show-video-box.html ולתקן זאת בעצמכם או לראות הקובץ המתוקן כאן ואת קוד המקור כאן.

+ +
+

הערה חשובה: אתם בטח שואלים את עצמכם מדוע לטרוח וליצור שני שלבים  - גם capturing וגם bubbling? התשובה נעוצה בהיסטוריה ובימי העבר כאשר התאימות בין דפדפנים הייתה שונה מאוד ולא כפי שהיא היום.

+ +

בימים ההם Netscape השתמש ב-event capturing בלבד ואילו Internet Explorer השתמש ב - event bubbling בלבד. כאשר ארגון W3C החליט לנסות וליצור סטדרט אחיד, הם החליטו על מנגנון שיכלול את שני השלבים - וכל הדפדפנים אימצו את שני השלבים.

+
+ +
+

לתשומת לב: יחד עם זאת, כברירת מחדל, כל מטפלי האירועים נרשמים בשלב bubbling ולא בשלב capturing וברוב המוחלט של הפעמים זה עושה שכל. אם אנחנו ממש רוצים לרשום אירוע בשלב ה-capturing, אנחנו יכולים לעשות זאת באמצעות הוספת true כפרמטר שלישי בתוך ()addEventListener. היכנסו לקישור זה אם תרצו להרחיב בנושא. 

+
+ +

Event delegation

+ +

bubbling מאפשר לנו להשתמש ביתרונות של event delegation — רעיון זה מתבסס על העובדה שאם אנחנו רוצים להריץ קוד מסויים כאשר אנחנו לוחצים על אלמנט ילד אחד שהוא חלק ממספר אלמנטים ילדים של אלמנט אב, אנחנו יכולים לקבוע את מאזין האירוע על אלמנט האב, ואז כאשר האירוע מתרחש על אחד מאלמנטים הילדים, האירוע ״יבועבע״ לאלמנט ההורה שלהם.

+ +

כתיבה שכזו עדיפה על רישום מאזין אירוע לכל אחד מהילדים בנפרד. להזכירכם - בשלב ה-bubbling נבדק האם האלמנט שהאירוע התרחש עליו מכיל מטפל אירוע לאירוע שהתרחש ומתקדם הלאה לאלמנט ההורה ומבעבע אליו את האירוע ובודק האם הוא מכיל מטפל אירוע לאירוע שהתרחש וכך הלאה.

+ +

דוגמא טובה לכך היא רשימה של פריטים - אם אנחנו רוצים שכל פריט מהרשימה יקפיץ הודעה כאשר לוחצים עליו, אנחנו יכולים לקבוע מאזין אירוע על האלמנט ההורה - במקרה שלנו <ul>, וכל לחיצה על פריט מהרשימה (<li>) -  כלומר כל התרחשות אירוע שכזה על פריט מהרשימה - אירוע הלחיצה יבעבע מאלמנט <li> לאלמנט האב - <ul>.

+ +

רעיון זה מוסבר בפירוט רב בבלוג של David Walsh עם דוגמאות נוספות. ראו את המאמר שלו בנושא How JavaScript Event Delegation Works.

+ +

לסיכום

+ +

במאמר זה ניסינו להסביר כל מה שאתם צריכים לדעת על אירועי Web בשלב זה. כפי שנאמר למעלה, אירועים הם לא חלק מה-core של JavaScript - הם מוגדרים ב-Web APIs של הדפדפן.

+ +

חשוב להבין בנוסף שיש הבדלים בין מודלי האירועים של JavaScript בסביסות השונות שהיא מורצת - החל מ- Web APIs ועד לסביבות אחרות כמו Browser WebExtensions ו- Node.js. לא מצפים מכם שכרגע תבינו את כל הסביבות הללו, אבל זה עוזר לכם להבין את הבסיס ככל ותתקדמו בלמידה.

+ +

אם משהו לא ברור, הרגישו חופשי לקרוא שוב את המאמר או ליצור עמנו קשר.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Return_values","Learn/JavaScript/Building_blocks/Image_gallery", "Learn/JavaScript/Building_blocks")}}

+ +

במודול זה

+ + diff --git a/files/he/learn/javascript/building_blocks/functions/index.html b/files/he/learn/javascript/building_blocks/functions/index.html new file mode 100644 index 0000000000..99255d0591 --- /dev/null +++ b/files/he/learn/javascript/building_blocks/functions/index.html @@ -0,0 +1,386 @@ +--- +title: Functions — פונקציות - חלקי קוד לשימוש חוזר +slug: Learn/JavaScript/Building_blocks/Functions +translation_of: Learn/JavaScript/Building_blocks/Functions +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Looping_code","Learn/JavaScript/Building_blocks/Build_your_own_function", "Learn/JavaScript/Building_blocks")}}
+ +

עקרון חשוב והכרחי נוסף בתכנות הוא פונקציות - functions. פונקציות מאפשרות לנו לאחסן קוד בתוך בלוק מוגדר ומבצע פעולה מסויימת, ואז לקרוא לאותו קוד מתי שנצטרך אותו באמצעות פקודה קצרה. זאת במקום לרשום את אותו קוד שוב ושוב. במאמר זה אנחנו נחקור את העקרונות הבסיסיים והחשובים שמאחורי פונקציות כמו הסינטקס הבסיסי שלהן, כיצד להגדיר אותן, כיצד להפעיל אותן, נלמד מהו סקופ ופרמטרים ועוד.

+ + + + + + + + + + + + +
ידע מוקדם:הכרות בסיסית עם המחשב ועם הבסיס של HTML ו- CSS, וכן סיום במלאו של מודול צעדים ראשונים ב-JavaScript.
מטרה:הבנה של עקרונות היסוד בנושא פונקציות ב-JavaScript.
+ +

איפה נמצא פונקציות?

+ +

ב-JavaScript אנחנו נמצא פונקציות בכל מקום. בעיקרון, אנחנו השתמשנו בפונקציות לאורך כל הדרך של הקורס, פשוט לא פירטנו עליהם לעומק. כעת אנחנו ניכנס לעומק של אלו ונבין כיצד להשתמש בהם.

+ +

כמעט כל פעם שאנחנו עושים שימוש בביטוי מסויים של JavaScript שעושה שימוש בסוגריים רגילות () וזה לא במסגרת לולאת for או לולאות while ו- do...while loop או משפטי תנאי if...else אנחנו בעצם עושים שימוש בפונקציות.

+ +

פונקציות מובנות (Built-in) של הדפדפן

+ +

אנחנו ביצענו לא מעט שימוש בפונקציות המובנות בדפדפן. בכל פעם שעשינו מניפולציה על מחרוזת לדוגמא:

+ +
let myText = 'I am a string';
+let newString = myText.replace('string', 'sausage');
+console.log(newString);
+// the replace() string function takes a source string,
+// and a target string and replaces the source string,
+// with the target string, and returns the newly formed string
+ +

או בכל פעם שעשינו מניפולציה על מערך:

+ +
let myArray = ['I', 'love', 'chocolate', 'frogs'];
+let madeAString = myArray.join(' ');
+console.log(madeAString);
+// the join() function takes an array, joins
+// all the array items together into a single
+// string, and returns this new string
+ +

או בכל פעם שרצינו ליצור מספר רנדומלי:

+ +
let myNumber = Math.random();
+// the random() function generates a random number between
+// 0 and up to but not including 1, and returns that number
+ +

אנחנו בעצם השתמשנו בפונקציות.

+ +
+

תשומת לבכם: נסו להכניס את השורות קוד הרשומות למעלה לקונסולה אם אתם לא זוכרים איך לעשות בהם שימוש.

+
+ +

ל- JavaScript יש לא מעט פונקציות מובנות אשר מאפשרות לנו לעשות דברים שימושיים מבלי לכתוב את כל הקוד בעצמנו. בפועל, חלק מהקוד שאנחנו מריצים כאשר אנחנו אנחנו קוראים לפונקציה מובנית של הדפדפן, לא יכל היה להירשם ב-JavaScript - הרבה מהפונקציות הללו קוראות לחלקים בקוד הדפדפן עצמו, אשר נבנה בשפה אחרת שאינה JavaScript כלל.

+ +

אנא זכרו שחלק מהפונקציות המובנות של הדפדפם אינן חלק מהבסיס של שפת JavaScript - חלקן מהן מוגדרות כחלק מה-API של הדפדפן, אשר בנוי מעל שפת הכתיבה של הדפדפן על מנת להעניק יותר פונקציונליות. אנחנו נסתכל על ה-API של הדפדפן בהמשך המודול. לרענון זכרונכם, ראו מאמר זה מתחילת הקורס.

+ +

functions vs. methods  - פונקציות מול מתודות

+ +

אנו קוראים לפונקציות שהן חלק מאובייקטים כ-מתודות (methods). אנחנו לא צריכים כרגע לדעת על המבנה הפנימי של אובייקטים ב-JavaScript - אנו נלמד את זה לעומק במודול הבא. לבינתיים, רק רצינו למנוע בלבול בין המושגים השונים. רוב הסיכויים שתשמעו את שניהם.

+ +

הקוד המובנה שעשינו בו שימוש לבינתיים מגיע ב-2 תצורות: פונקציות ו-מתודות. אתם יכולים לבדוק את הרשימה המלאה של פונקציות מובנות וכן את הרשימה המלאה של אובייקטים מובנים והמתודות שלהם פה.

+ +

כמו כן, ראינו הרבה פונקציות מותאמות -custom functions - פונקציות שאנחנו הגדרנו בעצמנו ולא מוגדרות בתוך הדפדפן עצמו. בכל פעם שאנחנו רואים שם שאינו שם שמור של השפה ולאחריו סוגריים רגילות (), זוהי פונקציה שהמפתח הגדיר בעצמו. בתרגול שלנו random-canvas-circles.html וגם בקוד המקור שלו במאמר בנושא לולאות, כללנו פונקציה ()draw שאנחנו בנינו שנראית כך :

+ +
function draw() {
+  ctx.clearRect(0,0,WIDTH,HEIGHT);
+  for (let i = 0; i < 100; i++) {
+    ctx.beginPath();
+    ctx.fillStyle = 'rgba(255,0,0,0.5)';
+    ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
+    ctx.fill();
+  }
+}
+ +

פונקציה זו מציירת 100 עיגולים אקראיים בתוך אלמנט {{htmlelement("canvas")}} . בכל פעם שאנחנו רוצים לעשות זאת, אנחנו יכולים להפעיל את הפונקציה עם הקוד הבא:

+ +
draw();
+
+ +

במקום לכתוב את כל הקוד שבתוך הפונקציה בכל פעם שאנחנו רוצים שיצוייר עיגול. 

+ +

פונקציות יכולות להכיל כל קוד שנרצה - אנחנו אפילו יכולים לקרוא לפונקציות אחרות מתוך פונקציות. הפונקציה למעלה לדוגמא, קוראת לפונקציה ()random שלוש פעמים, כפי שאנו רואים בקוד הבא:

+ +
function random(number) {
+  return Math.floor(Math.random()*number);
+}
+ +

אנחנו צריכים לבנות את הפונקציה ()random כי הפונקציה המובנית של הדפדפן ()Math.random מייצרת לנו מספר רנדומלי, אבל מספר רנדומלי עשרוני בין 0 ל-1. אנחנו לעומת זאת רצינו מספר רנדומלי שלם ולא עשרוני ושיהיה בין 0 למספר מסויים שאנחנו נגדיר לו.

+ +

Invoking functions - קריאה לפונקציה

+ +

ככל הנראה אתם כבר מבינים את הנושא, אבל בכל מקרה אנו מזכירים שכדי להשתמש בפועל בפונקציה אחרי שהיא הוגדרה, אנחנו צריכים להריץ אותה, לקרוא לה. בשפה האנגלית זה נקרא To invoke. זה נעשה באמצעות כתיבת שם הפונקציה איפה שנרצה בתוך הקוד שלנו, ולאחריו סוגריים מסולסלות ().

+ +
function myFunction() {
+  alert('hello');
+}
+
+myFunction()
+// calls the function once
+ +

Anonymous functions - פונקציות אנונימיות

+ +

אולי נתקלתם בפונקציות אשר מוגדרות ומופעלות בצורות אחרות. עד עכשיו, יצרנו פונקציה בצורה כזו:

+ +
function myFunction() {
+  alert('hello');
+}
+ +

אבל אנחנו גם יכולים ליצור פונקציה שאין לה שם:

+ +
function() {
+  alert('hello');
+}
+ +

פונקציה שכזו נקראת פונקציה אנונימית - anonymous function - אין לה שם. היא גם לא עושה כלום בעצמה. בדרך כלל אנחנו נשתמש בפונקציה אנונימית ביחד עם ״מטפל אירוע״ - event handler. לדוגמא, הקוד הבא יריץ את הקוד בנמצא בתוך הפונקציה, כאשר הכפתור myButton נלחץ:

+ +
var myButton = document.querySelector('button');
+
+myButton.onclick = function() {
+  alert('hello');
+}
+ +

הדוגמא למעלה דורשת שיהיה אלמנט {{htmlelement("button")}} זמין על גבי הדף כדי שנוכל לבחור אותו וללחוץ עליו. ראיתם מבנה שכזה מספר פעמים במהלך הקורס ואתם תלמדו עליו עוד בהמשך הקורס.

+ +

אנחנו יכולים להשים פונקציה אנונימית לתוך משתנה כך שהיא תהיה הערך של אותו משתנה. לדוגמא:

+ +
let myGreeting = function() {
+  alert('hello');
+}
+ +

ניתן להפעיל את הפונקציה הזו (invoke) באמצעות:

+ +
myGreeting();
+ +

בפועל, זה מעניק לשם פונקציה, למרות שהיא הייתה פונקציה אנונימית. אנחנו גם יכולים להשים את הפונקציה כך שהיא תהיה הערך של מספר משתנים. לדוגמא:

+ +
let anotherGreeting = myGreeting;
+ +

הפונקציה הזו יכולה להיות מופעלת בשתי הדרכים:

+ +
myGreeting();
+anotherGreeting();
+ +

אבל זה עלול להיות מבלבל, אז אל תעשו זאת. כשאנחנו יוצרים פונקציות, עדיף יהיה להיצמד למבנה הזה:

+ +
function myGreeting() {
+  alert('hello');
+}
+ +

אנחנו נשתמש בפונקציות אנונימיות בעיקר על מנת להריץ קוד בתגובה לאירוע שהתרחש - כמו לחיצה על כפתור - וזאת באמצעות ״מטפל אירוע״ - event handler. לדוגמא:

+ +
myButton.onclick = function() {
+  alert('hello');
+  // I can put as much code
+  // inside here as I want
+}
+ +

הפרמטרים של הפונקציה

+ +

חלק מהפונקציות דורשות שיינתנו להם פרמטרים מסויימים כשאנחנו מפעילים אותן - אלו בעצם ערכים שאנחנו צריכים לכלול בתוך הסוגריים הרגילות (), וזאת על מנת שהפונקציה תוכל לבצע את מה שהיא צריכה לבצע.

+ +
+

לתשומת לב: פרמטרים אלו נקראים ארגומנטים

+
+ +

כדוגמא, הפונקציה המובנית של הדפדפן לא דורשת שום פרמטרים. כשאנחנו קוראים לה, היא מחזירה מספר עשרוני בין 0 ל-1. ()Math.random:

+ +
let myNumber = Math.random();
+ +

הפונקציה המובנית של הדפדפן ()replace לעומת זאת, צריכה שני ארגומנטים - מחרוזת משנה שנרצה לחפש בתוך מחרוזת ראשית ואת המחרוזת המשנה שתחליף את זו שמצאנו בתוך המחרוזת הראשית:

+ +
let myText = 'I am a string';
+let newString = myText.replace('string', 'sausage');
+ +
+

שימו לב: כשאנחנו צריכים לציין מספר של ארגומנטים, אנחנו נפריד ביניהם באמצעות פסיק - ,.

+
+ +

חשוב לדעת כי לפעמים ארגומנטים יהיו אופציונליים - כלומר אנחנו לא נהיה חייבים לציין אותם. אם לא נציין אותם כאשר הם אופציונליים, הפונקציה בדרך כלל תאמץ סוג של התנהגות ברירת מחדל. לדוגמא, הפרמטר של פונקציה ()join של מערכים הוא אופציונלי:

+ +
let myArray = ['I', 'love', 'chocolate', 'frogs'];
+let madeAString = myArray.join(' ');
+// returns 'I love chocolate frogs'
+let madeAString = myArray.join();
+// returns 'I,love,chocolate,frogs'
+ +

אם לא נציין אותו, ערך ברירת המחדל הוא שיהיה התו המחבר - במקרה הזה זה יהיה פסיק ,.

+ +

סקופ של הפונקציה והתנגשויות

+ +

בוא נדבר מעט על {{glossary("scope")}} - עקרון חשוב מאוד להבנה כאשר אנחנו עוסקים בפונקציות. כאשר אנחנו יוצרים פונקציה, המשתנים וכל הדברים האחרים המוגדרים בתוך הפונקציה נמצאים בתוך scope נפרד, כלומר, הם נעולים בתוך מתחם מסויים, שלא ניתן לגשת אליו מחוץ לפונקציה.

+ +

הסקופ או התחום שנמצא מחוץ לכל הפונקציות שלנו נקרא global scope. ערכים שמוגדרים ב-global scope נגישים מכל מקום בקוד.

+ +

JavaScript נבנתה כך בצורה מסיבות מסויימות - אבל בעיקר מסיבות של אבטחה וארגון. לפעמים אנחנו לא נראה שמשתנים יהיו נגישים מכל מקום בקוד - סקריפטים חיצוניים שאנחנו מפעילים ממקומות אחרים יכולים לעשות לנו בלאגן ולגרום לשגיאות במקרה והם ישתמשו בשמות משתנים זהים ועלולים ליצור התנגשויות בין אם בטעות ובין אם מכוון.

+ +

לדוגמא, נניח ויש לנו קובץ HTML אשר קורא לשני קבצי JavaScript חיצוניים, ובשניהם יש משתנה ופונקציה מוגדרים שמשתמשים באותו שם:

+ +
<!-- Excerpt from my HTML -->
+<script src="first.js"></script>
+<script src="second.js"></script>
+<script>
+  greeting();
+</script>
+ +
// first.js
+var name = 'Chris';
+function greeting() {
+  alert('Hello ' + name + ': welcome to our company.');
+}
+ +
// second.js
+var name = 'Zaptec';
+function greeting() {
+  alert('Our company is called ' + name + '.');
+}
+ +

שתי הפונקציות שאנחנו רוצים לקרוא להם נקראות ()greeting, אבל אנחנו יכולים לגשת רק לפונקציה ()greeting שבקובץ second.js - שכן הקישור לקובץ מבוצע ב -HTML מאוחר יותר בקוד שלנו, ולכן המשתנים והפונקציה שלו דורסים את אלו שב- first.js.

+ +
+

לתשומת לב: ניתן לראות את הדוגמא ב-GitHub וכן את קוד המקור).

+
+ +

שמירה על הקוד שלנו נעול בתוך סקופ מונע בעיות שכאלו ונחשב כ- best practice.

+ +

ניתן לחשוב על זה כמו גן חיות. האריות, זברות, נמרים ופינגווינים נמצאים כל במתחמים נפרדים כל אחד, ויש להם גישה רק לדברים שנמצאים במתחם שלהם - בדיוק כמו בסקופים של פונקציות. אם הם היו יכולים להיכנס למתחמים אחרים, היו נוצרות לא מעט בעיות. במקרה הטוב, החיות האחרות היו מרגישות לא בנוח, במקרה הרע, הן היו נאכלות על ידי חיה אחרת.

+ +

+ +

למידה אקטיבית: לשחק עם ה-scope

+ +

נסתכל על דוגמא על מנת להבין מהו scope.

+ +
    +
  1. ראשית, צרו לעצמכם עותק של הדוגמא שלנו function-scope.html. הקובץ מכיל 2 פונקציות שנקראות ()a ו- ()b וכן שלושה משתנים - x, y, ו- z - שניים מתוכם מוגדרים בתוך פונקציות ואחד מתוכם מוגדר ב-global scope. בנוסף, הדוגמא גם מכילה פונקציה שלישית שנקראת ()output, אשר מקבלת ארגומנט אחד ומציגה אותו בתוך פסקה על גבי הדף.
  2. +
  3. פתחו את הדוגמא בדפדפן ובעורך הקוד שלכם.
  4. +
  5. הקלידו בקונסולה את הקוד הבא: +
    output(x);
    + אתם אמורים לראות שהערך של המשתנה x הוצג למסך.
  6. +
  7. כעת נסו להזין את הקוד הבא לקונסולה: +
    output(y);
    +output(z);
    + שתי הפקודות הללו יחזירו לנו שגיאה ביחד עם המשפט: "ReferenceError: y is not defined". מדוע? הסיבה נעוצה ב-scope של הפונקציות: - y ו- z נעולים בתוך הפונקציות ()a ו- ()b ולכן הפונקציה ()output לא יכולה לגשת אליהם כשהיא נקראת מה-global scope.
  8. +
  9. עם זאת, מה לדעתכם יקרה כשנקרא לפונקציה ()output מתוך הפונקציות? נסו לשנות את ()a ו- ()b שייראו כך: +
    function a() {
    +  let y = 2;
    +  output(y);
    +}
    +
    +function b() {
    +  let z = 3;
    +  output(z);
    +}
    + שמרו את הקוד ואז העלו מחדש את הדף בדפדפן ונסו לקרוא לפונקציות ()a ו- ()b מהקונסולה: + +
    a();
    +b();
    + אתם אמורים לראות את הערכים של y ו- z על גבי הדף. זה עובד מכיוון שהפונקציה ()output מופעלת מתוך פונקציה אחרת - כלומר מתוך אותו סקופ שבו מוגדרים המשתנים שהיא מדפיסה. הפונקציה ()output עצמה זמיני מכל מקום, שכן היא מוגדרת ב-global scope.
  10. +
  11. נסו עכשיו לעדכן את הקוד שלכם כך: +
    function a() {
    +  var y = 2;
    +  output(x);
    +}
    +
    +function b() {
    +  var z = 3;
    +  output(x);
    +}
    + רענון והעלו את הדף שוב והזינו את הקוד הבא בקונסולה:
  12. +
  13. +
    a();
    +b();
    + גם a() וגם b() מחזירים את הערך של x — 1. זה עובד מכיוון שלמרות ש-()output לא מוגדרת באותו סקופ ש- x מוגדר בו, אבל x הוא משתנה גלובלי אז הוא זמין בכל מקום בקוד.
  14. +
  15. לבסוף, עדכנו את הקוד כך: +
    function a() {
    +  var y = 2;
    +  output(z);
    +}
    +
    +function b() {
    +  var z = 3;
    +  output(y);
    +}
    + שמור ורענן את הדף. לאחר מכן הזן את הקוד הבא בקונסולה:
  16. +
  17. +
    a();
    +b();
    + הפעם כשקראנו ל- ()a ו- ()b אנחנו נקבל שגיאה מסוג "ReferenceError: z is not defined" זה מכיוון שביצוע הקוד ()output והמשתנים שהם מנסים להשיג לא מוגדרים בתוך אותו סקופ של פונקציה - המשתנים בעיקרון בלתי נראים לקריאות הפונציה הזו.
  18. +
+ +
+

לתשומת לבכם: אותו מנגנון סקופינג לא חל על לולאות { ... }(...) for ובלוקים של תנאים - { ... }(...) if הם אמנם נראים דומים, אבל הם לא אותו דבר. אל תתבלבלו.

+
+ +
+

לתשומת לבכם: השגיאה ReferenceError: "x" is not defined היא אחת מהשגיאות השכיחות שתיתקלו בה. אם קיבלתם שגיאה שכזו, וודאו שהגדרת את המשתנה הרלוונטי ובסקופ הרלוונטי.

+
+ + + +

פונקציות בתוך פונקציות

+ +

זכרו שאנחנו יכולים לקרוא לפונקציה מכל מקום, גם מתוך פונקציה אחרת. זה שימושי על מנת על מנת להשאיר את הקוד שלנו מסודר - אם יש לנו פונקציה אחת מורכבת וגדולה יהיה יותר ברור להבין אותה אם נפרק אותה לכמה פונקציות:

+ +
function myBigFunction() {
+  var myValue;
+
+  subFunction1();
+  subFunction2();
+  subFunction3();
+}
+
+function subFunction1() {
+  console.log(myValue);
+}
+
+function subFunction2() {
+  console.log(myValue);
+}
+
+function subFunction3() {
+  console.log(myValue);
+}
+
+ +

חשוב לוודא שהערכים שמבוצע בהם שימוש בתוך הפונקציה, מוגדרים בסקופ הנכון. הדוגמא למעלה תחזיר לנו שגיאה ReferenceError: myValue is not defined מכיוון שאמנם המשתנה myValue מוגדר באותו סקופ שהפונקציה נקראת, אך הוא לא מוגדר בתוך הפונקציות עצמן - בתוך הקוד שירוץ בפועל כשאנחנו קוראים לתתי פונקציות. על מנת לגרום לכך לעבוד, היינו צריכים להעביר אליהם את הפונקציה כפרמטר כמו שרשום בקוד מטה:

+ +
function myBigFunction() {
+  var myValue = 1;
+
+  subFunction1(myValue);
+  subFunction2(myValue);
+  subFunction3(myValue);
+}
+
+function subFunction1(value) {
+  console.log(value);
+}
+
+function subFunction2(value) {
+  console.log(value);
+}
+
+function subFunction3(value) {
+  console.log(value);
+}
+ +

לסיכום

+ +

מאמר זה סקר את העקרונות יסוד של פונקציות, על מנת לסלול את הדרך שלכם להבנה של כלים שימושיים נוספות ולהבנה כיצד לבנות פונקציה משלכם.

+ +

ראו גם

+ + + + + +

{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Looping_code","Learn/JavaScript/Building_blocks/Build_your_own_function", "Learn/JavaScript/Building_blocks")}}

+ +

במודול זה

+ + diff --git a/files/he/learn/javascript/building_blocks/index.html b/files/he/learn/javascript/building_blocks/index.html new file mode 100644 index 0000000000..e60d618b4e --- /dev/null +++ b/files/he/learn/javascript/building_blocks/index.html @@ -0,0 +1,51 @@ +--- +title: אבני הבנין של JavaScript +slug: Learn/JavaScript/Building_blocks +tags: + - JavaScript + - events + - אירועים + - לולאות + - מדריך + - ערכים מוחזרים מפונקציה + - פונקציות + - תנאים - Conditionals +translation_of: Learn/JavaScript/Building_blocks +--- +
{{LearnSidebar}}
+ +

במודול זה, אנחנו נמשיך להעמיק ביסודות ובמאפיינים והחשובים של JavaScript ונתמקד בסוגים שונים של קוד כגון משפטי תנאי (conditional statements),לולאות (loops), פונקציות (functions), ואירועים (events). חלק מהם כבר ראינו בשלבים קודמים של הקורס, אך לא העמקנו בהם. במודול זה ניכנס לעומק של אותן אבני בניין ונבין כיצד הן עובדות ומה מטרתן.

+ +

ידע מוקדם

+ +

לפני שתתחילו את המודול הזה, אנא וודאו כי הנכם בקיאים ביסודות HTML ושל CSS, וכן סיימתם לעבור על המודול הקודם שלנו צעדים ראשונים ב-JavaScript.

+ +
+

הערה: אם אתם עובדים על מחשב\טבלט\מכשיר אחר שאין לכם אפשרות ליצור עליו קבצים אישיים, אתם יכולים לנסות את (רוב) דוגמאות הקוד על תוכנות קוד אינטרנטיות כמו JSBin או Thimble.

+
+ +

מדריכים

+ +
+
קבלת החלטות בקוד - משפטי תנאי - Conditionals
+
כמו בכל שפת תכנות, קוד צריך לקבל החלטות ולבצע פעולות מסויימות בהתאם למקרים שונים. לדוגמא - במשחק, אם מספר הנסיונות המותרים של השחקן עבר את מספר הנסיונות המקסימלי שהוגדר, המשמעות היא שהמשחק הסתיים. או יישום אינטרנט של מזג אוויר אשר יציג למשתמש עיצוב מסויים של מזג האוויר בהתאם לשעה הנוכחית ביום, כך שבשעות היום יוצג עיצוב בהיר ובשעות הערב יוצג עיצוב כהה. במאמר זה אנחנו נחקור את המבנה של משפטי תנאי ב-JavaScript וכיצד הם עובדים.
+
לולאות - Loops
+
לפעמים אנחנו נצטרך לבצע את אותה פעולה או משימה ברצף, יותר מפעם אחת. לדוגמא -  כשנרצה לעבור רשימת שמות. בתכנות, לולאות יכולות לעשות את העבודה הזו בצורה מצויינת. במאמר זה אנחנו נחקור את המבנה של לולאות ב- JavaScript וכיצד הן עובדות.
+
פונקציות - בלוקי קוד לשימוש חוזר - Functions
+
קונספט הכרחי חשוב בתכנות הוא פונקציות. פונקציות מאפשרות לנו לאחסן חלקי קוד שמבצעים פעולה מסויימת בתוך בלוק מוגדר, ואז לקרוא לאותו קוד כשנצטרך להשתמש בו, באמצעות פקודה קצרה - וזאת במקום לרשום את אותו קוד פעם אחר פעם, כל פעם מחדש. במאמר זה נחקור את המבנה של פונקציה והרעיון העומד מאחוריה, ונבין מה הוא הסינטקס הבסיסי על מנת לרשום פונקציה, כיצד אנו קוראים לפונקציה ועוד. כמו כן, נלמד מהם ארגומנטים או פרמטרים אשר הפונקציות יכולות לקבל וכן מהו Scope.
+
בניית פונקציות משלנו
+
לאחר שנסיים לעבור על התיאוריה ונבין מהן פונקציות, במאמר זה נתרגל ונבין בצורה מעשית כיצד לבנות פונקציות משלנו, בהתאם לפעולת שנרצה לבצע. בהמשך הדרך, אנחנו נסביר גם פרטים שימושיים כיצד לטפל בפונקציות ובערכים שהן יכולות להחזיר לנו. 
+
ערכים מוחזרים מהפונקציה - Function return values
+
עקרון הכרחי וחשוב שאנחנו צריכים להכיר לגבי פונקציות הוא אילו ערכים פונקציות מחזירות לנו, אם בכלל. ישנן פונקציות שלא מחזירות ערכים לאחר שסיימו להריץ את הקוד שבתוכן, וישנן פונקציות שיחזירו לנו ערכים מסויימים. במאמר זה אנחנו נבין מהם אותם ערכים מוחזרים, כיצד אנחנו יכולים להשתמש בהם וכיצד אנחנו יכולים לגרום לפונקציות שלנו להחזיר ערכים. 
+
היכרות ראשונית עם אירועים -Introduction to events
+
אירועים אלו בעצם פעולות או התרחשויות אשר קורים במערכת, אשר אנחנו יכולים ״להאזין״ להם כך שנוכל להגיב בדרך מסויימת, ברגע שהם יתרחשו. לדוגמא, כאשר משתמש לוחץ על כפתור, אולי נרצה להגיב לאותה התרחשות, לאותו אירוע של לחיצת הכפתור על ידי הקפצת הודעה מסויימת. במאמר אחרון זה אנחנו נדון בכמה מהעקרונות החשובים בהקשר של אירועים, ונסתכל כיצד הם עובדים בדפדפנים.
+
+ +

תרגול

+ +

התרגול הבא יבדוק את ההבנה שלכם של החומר שנלמד במודול זה

+ +
+
בניית גלריית תמונות
+
אנו נתרגל שימוש בלולאות ופונקציות וכן בתנאים ואירועים על ידי בנייה של גלריית תמונות.
+
diff --git a/files/he/learn/javascript/building_blocks/looping_code/index.html b/files/he/learn/javascript/building_blocks/looping_code/index.html new file mode 100644 index 0000000000..b9067199e7 --- /dev/null +++ b/files/he/learn/javascript/building_blocks/looping_code/index.html @@ -0,0 +1,931 @@ +--- +title: לולאות +slug: Learn/JavaScript/Building_blocks/Looping_code +translation_of: Learn/JavaScript/Building_blocks/Looping_code +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/conditionals","Learn/JavaScript/Building_blocks/Functions", "Learn/JavaScript/Building_blocks")}}
+ +

שפות תכנות הן שימושיות מאוד כשזה קשור לביצוע משימות מסויימות שוב ושוב. מביצוע חישובים מתמטיים עד לכל דבר שאנחנו יכולים לחשוב עליו. במאמר זה נסתכל על מבנים שלו לולאות שזמינים עבורנו ב-JavaScript.

+ + + + + + + + + + + + +
ידע מוקדם:הכרות בסיסית עם המחשב ועם הבסיס של HTML ו- CSS, וכן סיום במלאו של מודול צעדים ראשונים ב-JavaScript.
מטרה:להבין כיצד להשתמש בלולאות ב-JavaScript ומתי.
+ +

מה הן לולאות?

+ +

לולאו הן עקרון חשוב מאוד בתכנות. לולאות קוד מכילות פעולות שנרצה לבצע שוב ושוב - ובשפה מקצועית - איטראציה - Iteration.

+ +

יש הרבה סוגי לולאות - אבל כולן עושות בעיקרון את אותו דבר: הן חוזרות על פעולה מסויימת מספר פעמים (ואף יכול להיות גם 0 פעמים).

+ +

ננסה להבין זאת באמצעות דוגמא פשוטה. נניח ויש לנו חקלאי אשר רוצה לוודא שיש לו מספיק אוכל למשפחה להמשך השבוע. הוא עשוי להשתמש בלולאה הבאה על מנת לעשות זאת:

+ +


+

+ +

ללולאה יהיו בדרך כלל אחד או יותר (לא בהכרח את כולם) מהמאפיינים הבאים:

+ + + +

למה צריך לולאות?

+ +

בשלב זה כנראה הבנו את הרעיון העומד מאחורי לולאות. כעת ננסה להבין כיצד זה עוזר לנו לבצע פעולות מסויימות שוב ושוב. 

+ +

בדרך כלל, הקוד שלנו יהיה מעט שונה בכל ריצה של הלולאה (כלומר - בכל איטראציה מוצלחת של הלולאה). דבר זה מאפשר לנו להשלים את ביצוען של כמות רבה של משימות דומות, אך שונות מעט. כך לדוגמא, אם יש לנו כמות רבה של חישובים שונים אשר נרצה לבצע קצת אחרת בכל ריצה/איטראציה.

+ +

נסתכל על דוגמא נוספת על מנת להסביר את הנושא. נניח שאנחנו רוצים לצייר 100 עיגולים אקראיים על אלמנט מסוג {{htmlelement("canvas")}}, ובאמצעות לחיצה על כפתור Update אנחנו נרצה לקבל סט חדש ואחר של 100 עיגולים אקראיים:

+ + + +

{{ EmbedLiveSample('Hidden_code', '100%', 400, "", "", "hide-codepen-jsfiddle") }}

+ +

אתם לא צריכים להבין את כל הקוד הרשום למעלה, אבל הסתכלו לעומק על החלק שמצייר בפועל 100 כדורים:

+ +
for (let i = 0; i < 100; i++) {
+  ctx.beginPath();
+  ctx.fillStyle = 'rgba(255,0,0,0.5)';
+  ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
+  ctx.fill();
+}
+ + + +

אתם מבינים את הרעיון - אנחנו משתמשים בלולאה על מנת לרוץ 100 איטראציות של הקוד הזה, כאשר בכל ריצה כזו נקבל עיגול במיקום אקראי אחר. אם נרצה יותר מ-100 עיגולים פשוט נשנה מספר אחד!.

+ +

אם לא היינו משתמשים בלולאה, היינו צריכים לרשום את הקוד הבא שוב ושוב בהתאם לכמות הפעמים שהיינו רוצים שיצוייר עיגול:

+ +
ctx.beginPath();
+ctx.fillStyle = 'rgba(255,0,0,0.5)';
+ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
+ctx.fill();
+ +

לולאת for

+ +

נחקור כיצד לולאות מסויימות בנויות. סוגי הלולאות השונים מאפשרים לנו דרכים שונות על מנת לקבוע את נקודת ההתחלה והעצירה של הלולאה.

+ +

הראשונה, שאנחנו נשתמש בה הרבה מאוד פעמים, היא לולאה מסוג for. לולאה זו היא בעלת הסינטקס הבא:

+ +
for (initializer; exit-condition; final-expression) {
+  // code to run
+}
+ +

הסבר:

+ +
    +
  1. המילה השמורה for, ולאחריה סוגריים רגילות ().
  2. +
  3. בתוך הסוגריים הרגילות () יש לנו 3 ביטויים, מופרדים על ידי ;: +
      +
    1. initializer  - מונה-מאתחל — פה אנו נראה בדרך כלל הצהרה על משתנה, בדרך כלל משתנה let אשר אנחנו נותנים לו ערך (מספר) התחלתי לפני שהלולאה רצה. הוא ישמש את הלולאה כמונה של מספר הריצה הרלוונטית. 
    2. +
    3. exit-condition - תנאי יציאה — זהו התנאי שנבדק בטרם כל איטרציה. אם תוצאת המבחן היא true, הלולאה תמשיך לרוץ והביטוי שבתוך הסוגריים המסולסלות יבוצע. אם תוצאת המבחן היא false הלולאה תפסיק לרוץ. תנאי היציאה הוא בדרך כלל ביטוי הכולל אופטורים להשוואה - מבחנים לבדיקה האם התקיים תנאי מסויים.
    4. +
    5. final-expression - iterator - ביטוי לקידום הלולאה — ביטוי זה יבוצע או ירוץ בכל פעם שהלולאה ביצעה ריצה/איטראציה במלואה. ביטוי זה משמש בדרך כלל להעלות (או להוריד) את המונה-מאתחל על מנת לקרב אותו לקיום תנאי היציאה.
    6. +
    7. שימו לב כי כל הביטויים האלו הם אופציונליים - אך לא ניכנס לאפשרויות השונות לעומק. אתם מוזמנים להרחיב בנושא בדף בנושא לולאת for
    8. +
    +
  4. +
  5. לאחר מכן יש לנו סוגריים מסולסלות {...} שכוללות בתוכן קוד אשר ירוץ בכל פעם שהלולאה מבצעת איטרציה.
  6. +
+ +

נסתכל על הדוגמא הבאה:

+ +
const cats = ['Bill', 'Jeff', 'Pete', 'Biggles', 'Jasmin'];
+let info = 'My cats are called ';
+const para = document.querySelector('p');
+
+for (let i = 0; i < cats.length; i++) {
+  info += cats[i] + ', ';
+}
+
+para.textContent = info;
+ +

הקוד למעלה יציג לנו את הפלט הבא:

+ + + +

{{ EmbedLiveSample('Hidden_code_2', '100%', 60, "", "", "hide-codepen-jsfiddle") }}

+ +
+

תשומת לב: ניתן למצוא את הקוד ב- GitHub או לראות אותו פה.

+
+ +

קוד זה מראה לולאת for שמבצעת איטרציה על הפריטים במערך ועושה משהו עם כל אחד מהם - זוהי תבנית שנראה שוב ושוב ב-JavaScript. בדוגמא זו למשל:

+ +
    +
  1. המונה: לפעמים גם נקרא כמאתחל, הינו משתנה i, והוא מתחיל ב-0.   (let i = 0).
  2. +
  3. בדיקת תנאי יציאה/עצירת הלולאה: הלולאה תרוץ כל עוד i קטן יותר ממספר האיברים שנמצאים במערך cats. (מציאת כמות האיברים שנמצאת במערך זה מתבצעת באמצעות cats.length. תנאי היציאה הוא חשוב ביצירת לולאה - הוא קובע מהו התנאי אשר רק כאשר תוצאות תהיה true, הלולאה תמשיך ותבצע איטרציה נוספת. במקרה הזה, כל עוד i < cats.length עדיין נכון, הלולאה תמשיך לרוץ.
  4. +
  5. הרצת הקוד שבתוך הסוגריים המסולסלות: בתוך הלולאה, אנחנו מחברים בין הפריט הנוכחי שהלולאה מבצעת עליו איטרציה [הערך של i באותה ריצה] cats,  ביחד עם פסיק ורווח בסוף המשתנה info: +
      +
    1. במהלך הריצה הראשונה - האיטרציה הראשונה, , i = 0, ולכן cats[0] + ', ' (שהוא שווה ל-Bill, ) יצורף לתוך info.
    2. +
    3. במהלך הריצה השנייה - האיטרציה השנייה , i = 1, ולכן cats[1] + ', ' (אשר שווה ל- Jeff, ) יצורך גם הוא לתוך info.
    4. +
    +
  6. +
  7. קירוב המונה לתנאי היציאה: אחרי כל ריצה של הלולאה, נוסיף 1 ל-i באמצעות ++iשימו לב - רק אחרי שהקוד שבתוך הסוגריים המסולסלות מבוצע, מתבצעת הוספה של 1 למשתנה i וכך הלאה.
  8. +
  9. ביצוע בדיקה חוזרת לתנאי העצירה ועמידה בו:  לאחר קירוב המונה לתנאי העצירה, תבוצע בדיקה חוזרת האם התנאי מתקיים -  כאשר תוצאת התנאי תהיה שוב true, הלולאה תמשיך ותבצע איטרציה נוספת.
  10. +
  11. רק כאשר i יהיה שווה ל- cats.length (במקרה זה, 5), הלולאה תפסיק שכן הערך המתקבל בתוצאה הוא false והדפדפן יעבור לקוד שמתחת לולאה. 
  12. +
+ +
+

לתשומת לבכם: רשמנו את תנאי היציאה כ- i < cats.length, ולא i <= cats.length, מכיוון שמחשבים מתחילים לספור מ-0 ולא מ-1 — אנחנו מתחילים כאשר i שווה ל0, וממשיכים עד אשר i = 4 (האינדקס של האיבר האחרון במערך).

+ +

 cats.length יחזיר 5, ומכיוון שאכן ישנם 5 פריטים, אבל הפריט החמישי של cats.length, נמצא באינדקס מס׳ 4. ולכן אנחנו לא רוצים את cats.length אלא את cats.length פחות אחד. אם נשים רק את cats.length, כאשר   i = 5  המבחן יחזיר לנו ערך של  undefined בעבור הפריט האחרון - שכן אין איבר באינדקס 5. ולכן, אנחנו נרצה להריץ את הלולאה מספר 1 פחות.

+
+ +
+

לתשומת לב: טעות נפוצה עם תנאי יציאה היא להשתמש עם (״שווה ל-״)  (===)  במקום עם (״קטן מ- או שווה ל-״) (<=) .

+ +

אם אנחנו נרצה להריץ את הלולאה שלנו עד אשר i = 5, תנאי היציאה יצטרך להיות i <= cats.length.אם נקבע אותו כ i === cats.length  אזי הלולאה לא תרוץ בכלל מכיוון ש-i לא שווה ל-5 באיטרציה הראשונה של הלולאה, ולכן הלולאה תעצור במיידי.

+
+ +

בעיה אחת קטנה שנותרה לנו היא שהמשפט בסופה של הלולאה לא מסודר כראוי במלואו שכן בריצה האחרונה גם הוספנו פסיק ולכן יש לנו פסיק בסוף המשפט.

+ +
+

My cats are called Bill, Jeff, Pete, Biggles, Jasmin,

+
+ +

באופן הגיוני, אנחנו נרצה לשנות את צורת חיבור המחרוזת כך שבאיטרציה האחרונה של הלולאה, לא נקבל פסיק בסוף המשפט. לשם כך אנחנו יכולים להכניס משפט if בתוך לולאת for שלנו על מנת לטפל במקרה זה:

+ +
for (let i = 0; i < cats.length; i++) {
+  if (i === cats.length - 1) {
+    info += 'and ' + cats[i] + '.';
+  } else {
+    info += cats[i] + ', ';
+  }
+}
+ +
+

לתשומת לב: ניתן למצוא את קוד הדוגמא הזו ב- GitHub או כ- דף אינטרנט).

+
+ +
+

זהירות: בלולאת for — כמו ביתר הלולאות, אנחנו צריכים לוודא שהמונה שלנו עולה או יורד, בהתאם למקרה הרלוונטי, כך שבשלב מסויים הוא יגיע לתנאי היציאה. אם לא - הלולאה תמשיך בלי סוף, ותגרום לכך שהדפדפן יעצור אותה או יקרוס. דבר כזה נקרא לולאה אינסופית.

+
+ +

יציאה מלולאות באמצעות break

+ +

אם אנחנו רוצים לצאת מלולאה לפני שכל האיטרציות הושלמו, אנחנו יכולים להשתמש בביטוי break. ראינו אותו בעבר כשלמדנו על משפטי תנאי מסוג switch (כאשר ביטוי מסויים עונה למקרה מסויים - break עוצר באופן מיידי את המשך הבדיקה וממשיך לקוד שלאחר משפט switch).

+ +

בדיוק אותו הדבר כמו עם לולאות - הביטוי break יגרום ליציאה מיידית מהלולאה והדפדפן ימשיך לקוד שנמצא לאחר מכן.

+ +

נניח ואנחנו רוצים לחפש בתוך מערך של אנשי קשר וטלפונים, ואז להחזיר רק את המספר שאנחנו רוצים למצוא? נתחיל ב-HTML פשוט - תיבת טקסט + {{htmlelement("input")}}, המאפשרת לנו להכניס את השם שנרצה לחפש ואלמנט מסוג כפתור {{htmlelement("button")}} על מנת לשלוח את החיפוש וכן אלמנט של פסקה  {{htmlelement("p")}} על מנת להציג בו את התוצאות.

+ +
<label for="search">Search by contact name: </label>
+<input id="search" type="text">
+<button>Search</button>
+
+<p></p>
+ +

כעת נכניס - JavaScript:

+ +
const contacts = ['Chris:2232322', 'Sarah:3453456', 'Bill:7654322', 'Mary:9998769', 'Dianne:9384975'];
+const para = document.querySelector('p');
+const input = document.querySelector('input');
+const btn = document.querySelector('button');
+
+btn.addEventListener('click', function() {
+  let searchName = input.value.toLowerCase();
+  input.value = '';
+  input.focus();
+  for (let i = 0; i < contacts.length; i++) {
+    let splitContact = contacts[i].split(':');
+    if (splitContact[0].toLowerCase() === searchName) {
+      para.textContent = splitContact[0] + '\'s number is ' + splitContact[1] + '.';
+      break;
+    } else {
+      para.textContent = 'Contact not found.';
+    }
+  }
+});
+ + + +

{{ EmbedLiveSample('Hidden_code_3', '100%', 100, "", "", "hide-codepen-jsfiddle") }}

+ +
    +
  1. ראשית - הגדרנו קבועים - יש לנו מערך עם פרטי קשר - כאשר כל איבר במערך הוא מחרוזת המכילה שם ומספר טלפון המופרדים על ידי :. הגדרנו קבוע בשם para שמקבל הפנייה לאלמנט <p>. הגדרנו קבוע בשם input שמקבל הפניה לאלמנט <input> וקבוע בשם btn שמקבל הפניה ל-<button>
  2. +
  3. לאחר מכן חיברנו ״מאזין אירוע״ לכפתור - (btn), כך שבכל פעם שהוא יילחץ ירוץ קוד מסויים לביצוע החיפוש ויחזיר את התוצאה (event handler). במקרה הזה, זו הפונקציה האנונימית שנמצאת מיד לאחר הביטוי 'click'.
  4. +
  5. אחסנו את הערך שהוכנס לתוך תיבת הטקסט (input)  בתוך משתנה שנקרא searchName, לאחר מכן ריקנו את תיבת הטקסט מתוכן, ועשינו עליה פוקוס באמצעות מתודת ()focus , על מנת שתהיה מוכנה לחיפוש הבא. שימו לב שאנחנו גם הרצנו את מתודת ()toLowerCase על הערך שהתקבל ב-input כדי לנרמל את המחרוזת. 
  6. +
  7. ועכשיו לחלק המעניין של לולאת ה-for: +
      +
    1. אנחנו מתחילים את המונה ב-0, מתבצעת בדיקת עמידה בתנאי, ככל והערך המוחזר הוא true, מתבצעת איטרציה - הרצה של הקוד שבתוך הסוגריים המסולסלות של הלולאה: +
        +
      1. בתוך הלולאה אנחנו תחילה מחלצים כל חלק מהמחרוזת הראשית באמצעות מתודה שאנחנו מכירים ()split, אשר מקבלת את התו : כתו שיחצה את המחרוזת contacts בכל פעם שהמתודה תמצא את התו הזה. להזכירכם מתודה זו מחזירה מערך של מחרוזות שהופרדו על ידי התו שהיא קיבלה. במקרה הזה אנחנו מאחסנים במשתנה בשם splitContact את המערך החדש שהוחזר לנו בכל איטרציה שזה בעצם מערך עם שני איברים: שם ומספר. 
      2. +
      3. לאחר מכן אנחנו משתמשים במשפט תנאי לבדוק האם [splitContact[0 שזה בעצם שם האדם מנורמל באמצעות()toLowerCase, שווה לטקסט שנמצא ב-searchName. אם כן, אנחנו נכניס מחרוזת לתוך הפסקה עם הטלפון שלו שזה בעצם [splitContact[1, ונשתמש ב-break על מנת לעצור את הלולאה. 
      4. +
      +
    2. +
    3. לאחר מכן מתבצעת הגדלת של ה-i ב-1 בכל איטרציה מוצלחת של הלולאה באמצעות ++i.
    4. +
    +
  8. +
  9. אחרי כל האיטרציות, כאשר i יהיה שווה לאיבר האחרון במערך של המחרוזת הראשית - כלומר אחרי (contacts.length-1) אם searchName לא זהה לאף  [splitContact[i, אז טקטסט של הפסקה הופך ל- "Contact not found."  
  10. +
+ +
+

לתשומת לב: ניתן למצוא את קוד המקור - GitHub code on GitHub או כדף אינטרנט.

+
+ +

דילוג על איטרציה עם continue

+ +

ביטוי ה-continue עובד בדרך דומה לביטוי break, רק שבמקום לעצור את הלולאה ולצאת ממנה, הוא פשוט ממשיך לאיטרציה הבאה של הלולאה. נעבור כעת על דוגמא נוספת שבה אנחנו נזין מספר מקבל מספר כערך, ומחזיקה רק המספרים שהם מספרים שלמים.

+ +

ה-HTML  בעיקרון דומה לדוגמא הקודמת - יש לנו תיבת טקסט פשוטה ופסקה להציג את הפלט. ה-JavaScript גם דומה, למרות שהלולאה שלנו קצת אחרת:

+ +
let num = input.value;
+
+for (let i = 1; i <= num; i++) {
+  let sqRoot = Math.sqrt(i);
+  if (Math.floor(sqRoot) !== sqRoot) {
+    continue;
+  }
+
+  para.textContent += i + ' ';
+}
+ +

זה הפלט שלנו:

+ + + +

{{ EmbedLiveSample('Hidden_code_4', '100%', 100, "", "", "hide-codepen-jsfiddle") }}

+ +
    +
  1. במקרה הזה, הקלט צריך להיות מספר - num. אנו נותנים ללולאת ה-for מונה שמתחיל ב-1 (אנחנו לא מעוניינים ב- 0 במקרה הנוכחי), תנאי יציאה שאומר שהלולאה תפסיק כאשר המונה יהיה גדול מהמספר שהכנסנו - מ-num, ואז ביטוי העלאה שמוסיף למונה 1 בכל איטרציה. 
  2. +
  3. בתוך הלולאה, אנחנו מוצאים את השורש הריבועי של כל מספר (של כל num) באמצעות שימוש במתודה ()Math.sqrt, ואז בודקים האם השורש הריבועי הוא שלם על ידי בדיקה האם הוא זהה לעצמו כשהוא מעוגל כלפי מטה לשלם הקרוב - זה מה שמתודת ()Math.floor עושה למספר שמועבר אליה - היא מחזירה את המספר השלם הגדול ביותר אשר נמוך מהמספר שהבאנו לה או השווה לו.
  4. +
  5. אם השורש הריבועי והמספר שעוגל כלפי מטה אינהם זהים אחד לשני - (!==), המשמעות היא שהשורש הריבועי הוא לא מספר שלם, ולכן אנחנו לא מעוניינים בו. במקרה כזה, אנחנו נשתמש בביטוי continue על מנת לעבור לאיטרציה הבאה, אבל מבלי להמשיך להריץ את קוד אשר נמצא בהמשך האיטרציה הנוכחית (וביתר האיטרציות) ומבלי לצאת מהלולאה.
  6. +
  7. אם השורש הריבוע הוא מספר שלם, אנחנו לא עומדים בתנאי שרשום במשפט ה-if ולכן המשפט continue לא מורץ. במקום, אנחנו מצרפים את הערך שבתוך i בצירוף רווח, לסוף של הטקסט שבתוך הפסקה. 
  8. +
+ +
+

לתשומת לב: ניתן לראות את  קוד המקור ב-GitHub או לראות את הדף אינטרנט.

+
+ +

while ו-do ... while

+ +

לולאות for הן לא הלולאות היחידות שיש לנו ב-JavaScript. האמת שיש עוד הרבה אחרות. אנחנו ללא צריכים לדעת את כולן כעת, אבל שווה יהיה להעיף מבט בכמה ונבין שאפשרויות שונות עובדים בצורה שונה.

+ +

לולאת while מורכבת מהסינטקס הבא:

+ +
initializer
+while (exit-condition) {
+  // code to run
+
+  final-expression
+}
+ +

לולאה זו עובדת בצורה דומה ללולאת for, למעט העובדה שהערך המאתחל נקבע לפני הלולאה, והביטוי שיביא למימוש תנאי היציאה יהיה כלול בתוך הסוגריים המסולסלות {}. תנאי היציאה נכלל בתוך המרכאות העגולים, כאשר לפני המרכאות יש את המילה השמורה while ולא for.

+ +

משפטי while ממשיכים לפעול עד שהתנאי המופיע בראש המשפט אינו נכון עוד. שימו לב שניתן להכניס בלולאה זו את את כל שלושת הביטויים המוכרים לנו מלולאת for - ערך מאתחל (לא חובה), תנאי יציאה וביטוי  סופי שיבוצע בסוף האיטרציה (לא חובה). כלומר, הערך היחיד שחובה לכלול בלולאת while הוא התנאי ליציאה - אך יחד עם זאת, ראו הערה חשובה בסוף פסקה זו בדבר סיום ריצת הלולאה. 

+ +

בוא נסתכל שוב על רשימת החתולים, אבל נכתוב אותה באמצעות לולאת while:

+ +
let i = 0;
+
+while (i < cats.length) {
+  if (i === cats.length - 1) {
+    info += 'and ' + cats[i] + '.';
+  } else {
+    info += cats[i] + ', ';
+  }
+
+  i++;
+}
+ +
+

לתשומת לב: זה עובד כמו שציפינו — ראו את הדף עובד ב-GitHub או את קוד המקור).

+
+ +

לולאת do...while דומה מאוד ללולאת while אבל שונה מעט:

+ +
initializer
+do {
+  // code to run
+
+  final-expression
+} while (exit-condition)
+ +

במקרה הזה, המאתחל מגיע שוב ראשון, לפני שהלולאה מתחילה. המילה שמורה do ולאחר מכן סוגריים מסולסלות {} שבותכן ייכנס הקוד שנרה שירוץ בלולאה. ולסוף , המילה השמורה while ולאחרי קוד היציאה.

+ +

השוני כאן זה שתנאי היציאה מגיע בסוף, עטוף בתוך סוגריים רגילות (). בלולאת do...while, הקוד בתוך הסוגריים המסולסלות {...} תמיד ירוץ פעם אחת לפחות לפני בדיקת התנאי ואז יבדוק את התנאי על מנת לבדוק האם לרוץ שוב. להזכירכם - בלולאות while ובלולאות for, בדיקת התקיימות התנאי מתבצעת לפני הרצת הקוד שבתוך {...}  כך שיכול להיות שהקוד בלולאות אלו לא יבוצע לעולם. בלולאת do...while לעומת זאת, הקוד תמיד ירוץ פעם אחת לפחות.

+ +

בוא נכתוב את הדוגמא שלנו באמצעות הלולאה do...while:

+ +
let i = 0;
+
+do {
+  if (i === cats.length - 1) {
+    info += 'and ' + cats[i] + '.';
+  } else {
+    info += cats[i] + ', ';
+  }
+
+  i++;
+} while (i < cats.length);
+ +
+

לתשומת לב: הלולאה עובדת בדיוק כפי שרצינו - ראו ב- GitHub וכן את קוד המקור.

+
+ +
+

זהירות: בלולאות while  וב-do...while - אנחנו חייבם לוודא שהמאתחל מועלה או, בהתאם למקרה, יורד, כך שבסופו של דבר הקוד יגיע לתנאי היציאה והלולאה תסתיים. אחרת, הלולאה תמשיך עד אינסוף. במקרה כזה הדפדפן יכריח אותה להפסיק או שהוא יקרוס. זה נקרא לולאה אינסופית.

+
+ +

למידה עצמאית: בניית שעון ספירה לאחור

+ +

בתרגיל זה, אנחנו נרצה שתבנה תוכנית שתדפיס שעון עצר מ-10 ל-0 וכן:

+ + + + +

אם עשיתם טעות אתם תמיד יכולים לאתחל את הקוד באמצעות הכפתור "Reset" ואם ממש נתקתעם לחצו על כפתור "Show solution" לפתרון.

+ + + +

{{ EmbedLiveSample('Active_learning', '100%', 880, "", "", "hide-codepen-jsfiddle") }}

+ +

למידה עצמאית - מילוי של רשימת אורחים

+ +

+ בתרגיל זה, אנחנו רוצים שתיקחו רשימה של שמות שמאוחסנים במערך ותכניסו אותם לתוך רשימת אורחים. זה לא כזה קל - אנחנו רוצים רשימת אורחים שמורשים להיכנס ורשימת אורחים שלא מורשים להיכנס.

+ +

אתם מתבקשים לבצע את הדברים הבאים:

+ + + +

לבינתיים סיפקנו לכם:

+ + + +

+ שאלת בונוס - אחרי השלמת המשימה, אתם תישארו עם 2 רשימת שמות, מופרדות על ידי פסיקים, אבל לא מסודרות, שכן בסוף כל רשימה יש לנו פסיק. + מה ניתן לעשות כדי לחתוך את אותו פסיק או לבטל אותו? הסכתלו על +מתודות מחרוזות שימושיות לעזרה.

+ +

אם עשיתם טעות אתם תמיד יכולים לאתחל את הקוד באמצעות הכפתור "Reset" ואם ממש נתקתעם לחצו על כפתור "Show solution" לפתרון

+ + + +

{{ EmbedLiveSample('Active_learning_2', '100%', 680, "", "", "hide-codepen-jsfiddle") }}

+ +

באיזו לולאה עלינו להשתמש??

+ +

+ בדרך כךך, לשימושים בסיסים, הלולאות for, while, ו-do...while, הן חלופיות. כולן לרוב יכולות לפתור את אותן בעיות ואתם תחליטו במה לבחור.

+ +

תחילה לולאת for:

+ +
for (initializer; exit-condition; final-expression) {
+  // code to run
+}
+ +

לולאת while:

+ +
initializer
+while (exit-condition) {
+  // code to run
+
+  final-expression
+}
+ +

לולאת do...while:

+ +
initializer
+do {
+  // code to run
+
+  final-expression
+} while (exit-condition)
+ +

+ אנחנו ממליצים על לולאת _____, לפחות בהתחלה, כיוון שהיא לרוב הקלה ביותר לזכור - המאתחל, תנאי היציאה ומקדם/מחסיר, אשר כולם נכנסים בתוך הסוגריים הרגילות וכך קל לבדוק שלא שכחנו כלום.

+ +
+

לתשומת לב: + יש סוגי לולאות נוספים ואפשרויות נוספות ללולאות, גם לאלו שסקרנו במאמר זה. אפשרויות ולולאות אלו הן מאוד שימושיות במקרים מתקדמים או פרטניים ולא נגע בהם במאמר זה. אם תרצו להעמיק, ראו את הדף בנושא + Loops and iteration guide.

+
+ +

לסיכום

+ +

+ מאמר זה נועד להעניק לכם את העקרונות הבסיסים והאפשרויות העומדות בפניהם כאשר תרצו לבצע לולאה של קוד. אתם אמורים בלשב זה להבין את הרעיון והטכניקה שבה לולאות עובדות על מנת לבצע את אותו קוד שוב ושוב.

+ +

ראו גם

+ + + +

{{PreviousMenuNext("Learn/JavaScript/Building_blocks/conditionals","Learn/JavaScript/Building_blocks/Functions", "Learn/JavaScript/Building_blocks")}}

+ +

במודול זה

+ + diff --git a/files/he/learn/javascript/building_blocks/return_values/index.html b/files/he/learn/javascript/building_blocks/return_values/index.html new file mode 100644 index 0000000000..52e224289b --- /dev/null +++ b/files/he/learn/javascript/building_blocks/return_values/index.html @@ -0,0 +1,180 @@ +--- +title: return values - ערכים המוחזרים מפונקציה +slug: Learn/JavaScript/Building_blocks/Return_values +tags: + - Beginner + - Functions + - JavaScript + - Return values + - מדריך + - ערכים מוחזרים + - פונקציות +translation_of: Learn/JavaScript/Building_blocks/Return_values +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Build_your_own_function","Learn/JavaScript/Building_blocks/Events", "Learn/JavaScript/Building_blocks")}}
+ +

עקרון חשוב שנותר לנו לדון בו בהקשר של פונקציות הוא הערכים שהפונקציות יכולות להחזיר - return values. יש פונקציות שלא מחזירות ערך משמעותי אחרי שהן סיימו, אבל אחרות כן וזה חשוב שנבין מהם אותם ערכים, כיצד אנחנו יכולים לעשות בהם שימוש ואיך לגרום לפונקציות שאנחנו בונים להחזיר ערכים שנוכל להשתמש בהם. במאמר זה נדון בהיבטים אלו.

+ + + + + + + + + + + + +
ידע מוקדם: +

הכרות בסיסית עם המחשב ועם הבסיס של HTML ו- CSS, סיום במלואו של מודול צעדים ראשונים ב-JavaScript. וכן, את המאמר בנושא Functions — פונקציות - חלקי קוד לשימוש חוזר.

+
מטרה:להבין מהם return values, וכיצד להתשמש בהם.
+ +

מה הם return values?

+ +

Return values הם בדיוק כמו שהם נשמעים - אלו ערכים שמוחזרים על ידי הפונקציה כאשר היא מסיימת. אנחנו כבר ראינו return values במספר פעמים, למרות שאולי לא חשבנו עליהם כך. נחזור לקוד שאנחנו מכירים:

+ +
var myText = 'I am a string';
+var newString = myText.replace('string', 'sausage');
+console.log(newString);
+// the replace() string function takes a string,
+// replaces one substring with another, and returns
+// a new string with the replacement made
+ +

ראינו את הקוד הזה בעבר במאמר הראשון בנושא פונקציות. אנחנו קוראים/מפעילים את הפונקציה ()replace על המחרוזת myText ומעבירים לה שני פרמטרים (ארגומנטים) - את המחרוזת משנה('string') שהיא צריכה לחפש במחרוזת הראשית (myText) ואת המחרוזת משנה החדשה שתחליף את המחרוזת משנה שנמצאה ('sausage'). כאשר פונקציה זו מסיימת - משלימה את הריצה שלה, היא מחזירה ערך, שהוא בעצם המחרוזת החדשה עם ההחלפה שבוצgה. בקוד למעלה, אנחנו שומרים את אותו ערך מוחזר כערך של המשתנה newString שלנו.

+ +

אם תעיפו מבט על הדף שלנו בנושא פונקציית ()replace, אתם תראו חלק שנקרא Return value. תמיד חשוב לדעת ולהבין אלו ערכים מוחזרים על ידי פונקציה, על מנת שנוכל להשתמש בהם אם נרצה או כשנצטרך.

+ +

חלק מהפונקציות לא מחזירות return value. במקרים כאלו, הערך המוחזר יהיה void או undefined. לדוגמא, בפונקציה ()displayMessage שבנינו במאמר הקודם, אין ערך מוחזר כתוצאה מהשלמת ריצת הפונקציה. היא רק גרמה לקופסא להיות מוצגת איפשהו על המסך.

+ +

באופן כללי, return value משמש כאשר הפונקציה היא שלב ביניים בחישוב כלשהו שאנחנו מבצעים לשם קבלת תוצאה סופית. ערכים מוחזרים אלו צריכים להיות מחושבים על ידי הפונקציה, והיא מחזירה את הערכים הללו בתור התוצאות של הקריאה לה (הריצה שלה), ובתוצאות הללו ניתן להשתמש בשלב הבא של החישוב.

+ +

שימוש ב- return values בפונקציות שלנו

+ +

על מנת להחזיר ערך מפונקציה שאנחנו בונים, אנחנו צריכים להשתמש במילה השמורה return. ראינו מילה זו בפעולה לאחרונה בתרגול שלנו בנושא random-canvas-circles.html. פונקציית ()draw שלנו מציירת 100 עיגולים אקראיים על האלמנט {{htmlelement("canvas")}}:

+ +
function draw() {
+  ctx.clearRect(0,0,WIDTH,HEIGHT);
+  for (var i = 0; i < 100; i++) {
+    ctx.beginPath();
+    ctx.fillStyle = 'rgba(255,0,0,0.5)';
+    ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
+    ctx.fill();
+  }
+}
+ +

בכל איטרציה של הלולאה, מבוצעות שלוש קריאות לפונקציה ()random, על מנת לייצר מספר אקראי לקוארדינטות x ו-y של העיגול הנוכחי וכן לרדיוס שלו. הפונקציה ()random מקבלת ארגומנט אחד - מספר שלם - ומחזירה מספר שלם בין 0 לאותו מספר שלם שהכנסנו לה כארגומנט. זה נראה כך:

+ +
function randomNumber(number) {
+  return Math.floor(Math.random()*number);
+}
+ +

הקוד למעלה היה יכול להירשם גם כך:

+ +
function randomNumber(number) {
+  var result = Math.floor(Math.random()*number);
+  return result;
+}
+ +

אבל הגרסה הראשונה של הקוד קלה יותר לכתיבה וגם קומפקטית יותר.

+ +

אנחנו מחזירים את התוצאה של החישוב (Math.floor(Math.random()*number בכל פעם שקוראים לפונקציה. הערכים המוחזרים הללו מופיעים ברגע שהפונקציה נקראת (מופעלת), והקוד ממשיך. לדוגמא, אם נריץ את השורות הבאות:

+ +
ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
+ +

ושלושת הקריאות לפונקציה ()random החזירו נניח את הערכים 500, 200, ו- 35, בהתאמה, השורה תרוץ בפועל כאילו היא נכתבה כך :

+ +
ctx.arc(500, 200, 35, 0, 2 * Math.PI);
+ +

הקריאות לפונקציה באותה שורה רצות קודם והערכים המוחזרים של אותן קריאות נכנסים לתוך השורה עוד לפני ששורת הקוד עצמה מורצת במלואה.

+ +

למידה עצמאית: הגדרת - return value של הפונקציה שלנו

+ +

בתרגול זה אנחנו נכתוב פונקציות משלנו הכוללות return values.

+ +
    +
  1. ראשית, שמרו עותק מקומי של הקובץ function-library.html מ-GitHub. זהו דף HTML פשוט המיכל שדה טקסט {{htmlelement("input")}} ופסקה. בנוסף יש גם אלמנט {{htmlelement("script")}} כאשר בתוכו עשינו הפנייה לשני האלמנטים של ה-HTML בתוך שני משתנים. דף זה יאפשר לנו להכניס מספר כלשהו לתוך תיבת טקסט, ולהציג חישובים שונים על המספר הזה בתוך הפסקה שמתחת.
  2. +
  3. כעת, נוסיף פונקציות בתוך <script>. מתחת לשתי השורות הקיימות של JavaScript, הוסיפו את הגדרות הפונקציות הבאות: +
    function squared(num) {
    +  return num * num;
    +}
    +
    +function cubed(num) {
    +  return num * num * num;
    +}
    +
    +function factorial(num) {
    +  var x = num;
    +  while (x > 1) {
    +    num *= x-1;
    +    x--;
    +  }
    +  return num;
    +}
    + הפונקציות ()squared ו- ()cubed דיי ברורות - הן מחזירות את תוצאות ההכפלה או את השילוש של מספר שניתן להן כפרמטר, בעצמו. הפונקציה ()factorial מחזירה את תוצאת העצרת של מספר מסויים. אם אתם לא זוכרים מה זה עצרת, ראו הסבר על הערך בויקיפדיה.
  4. +
  5. כעת, אנחנו הולכים להוסיף דרך להדפיס את כל המידע הזה לגבי המספר שהכנסנו. הכניסו את הקוד הבא, מתחת לפונקציות הנוכחיות: +
    input.onchange = function() {
    +  var num = input.value;
    +  if (isNaN(num)) {
    +    para.textContent = 'You need to enter a number!';
    +  } else {
    +    para.textContent = num + ' squared is ' + squared(num) + '. ' +
    +                       num + ' cubed is ' + cubed(num) + '. ' +
    +                       num + ' factorial is ' + factorial(num) + '.';
    +  }
    +}
    + +

    הוספנו פונקציה בתור ״מטפל אירוע״ אשר תרוץ כל פעם שאירוע מסוג onchange החל להתרחש בשדה הטקסט שלנו (input), כלומר - כל פעם שמוכנס ערך חדש לתוך שדה הטקסט והערך הזה הוגש - כלומר לחצנו על אנטר או עברנו לאלמנט אחר בדף. כאשר פונקציה אנונימית זו רצה, הערך שהוכנס לתוך שדה הטקסט מאוחסן בתוך המשתנה num.

    +
  6. +
  7. +

    לאחר מכן, אנחו מבצעים בדיקה באמצעות משפט תנאי -

    + +
      +
    1. +

      אם הערך שהוכנס אינו מספר, אנחנו נציג הודעת שגיאה לתוך הפסקה. המבחן שלנו מבצע שימוש בפונקציית ()isNaN אשר בודקת האם הערך שהוכנס ב-num הוא לא מספר. אם הערך שהוכנס הוא מספר - היא מחזירה false ואם הוא לא מספר היא מחזירה true.

      +
    2. +
    3. +

      אם המבחן שלנו החזיר false, אז הערך של num הוא מספר ואנחנו יכולים להדפיס לתוך האלמנט p שלנו מהו תוצאת ההכפלה, השילוש והעצרת שלו. המשפט שלנו קורא לפונקציות ()squared(), cubed, ו- ()factorial על מנת לקבל את הערכים הללו.

      +
    4. +
    +
  8. +
  9. שמרו את הקוד ונסו אותו בדפדפן שלכם.
  10. +
+ +
+

לתשומת לב: אם נתקלתם בבעיות בתוכנית או אתם לא מצליחים לגרום לקוד שלכם לעבוד, נסו להשוו אותו לגרסה הסופית שלנו ב-GitHub או ראו אותו כדף אינטרנט.

+
+ +

תרגיל זה ניסה להציג לכם כמה מהנקודות החשובות של ביטוי return. בנוסף:

+ + + +

לסיכום

+ +

במאמר זה ובשני המאמרים הקודמים למדנו על פונקציות, כמה הן שימושיות וכיצד ניתן להשתמש בהם. יש כמובן הרבה מה להוסיף על פונקציות בנוגע לסינטקס שלהם ולפונקציונליות שלהם, שלושת המאמרים האחרונים בנושא פונקציות ניסו להסביר לכם את עקרונות היסוד והבסיס. הרגישו חופשי להרחיב את הידיעות שלכם בנושא בקישורים המופיעים מטה.

+ +

ראו גם

+ + + +

{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Build_your_own_function","Learn/JavaScript/Building_blocks/Events", "Learn/JavaScript/Building_blocks")}}

+ +

במודול זה

+ + diff --git "a/files/he/learn/javascript/building_blocks/\327\252\327\240\327\220\327\231\327\235/index.html" "b/files/he/learn/javascript/building_blocks/\327\252\327\240\327\220\327\231\327\235/index.html" new file mode 100644 index 0000000000..4c5c5dcc54 --- /dev/null +++ "b/files/he/learn/javascript/building_blocks/\327\252\327\240\327\220\327\231\327\235/index.html" @@ -0,0 +1,789 @@ +--- +title: משפטי תנאי - קבלת החלטות בקוד שלנו +slug: Learn/JavaScript/Building_blocks/תנאים +tags: + - Conditionals + - Switch + - else if + - if ... else + - ternary + - אופרטור טרנארי + - משפטי אם...אחר + - משפטי תנאי + - תנאים +translation_of: Learn/JavaScript/Building_blocks/conditionals +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/JavaScript/Building_blocks/Looping_code", "Learn/JavaScript/Building_blocks")}}
+ +

כמו בכל שפת תכנות, הקוד שלנו צריך ״לקבל החלטות״ בעצמו ולבצע פעולות מסויימות בהתאם למקרים שונים. לדוגמא - במשחק, אם מספר הנסיונות המותרים של השחקן עבר את מספר הנסיונות המקסימלי שהוגדר, המשמעות היא שהמשחק הסתיים. דוגמא נוספת היא יישום אינטרנט של מזג אוויר אשר יציג למשתמש עיצוב מסויים של מזג האוויר בהתאם לשעה הנוכחית ביום, כך שבשעות היום יוצג עיצוב בהיר ובשעות הערב יוצג עיצוב כהה. במאמר זה אנחנו נחקור את המבנה של משפטי תנאי ב-JavaScript וכיצד הם עובדים.

+ + + + + + + + + + + + +
ידע מוקדם:הכרות בסיסית עם המחשב ועם הבסיס של HTML ו- CSS, וכן סיום במלאו של מודול צעדים ראשונים ב-JavaScript.
מטרה:להבין כיצד להשתמש במשפטי תנאי ב-JavaScript.
+ +

תנאים והתניות בחיים האמיתיים

+ +

בני האדם מקבלים החלטות שמשפיעות על החיים שלהם באופן קבוע, מהחלטה קטנה האם לאכול שתי עוגיות או אחת עד להחלטות מורכבות האם לעזוב את העבודה או האם ללכת ללמוד אסטרונומיה במקום סוציולוגיה.

+ +

משפטי תנאי ב-JavaScript אפשרים לנו לייצג בקוד שלנו את התהליך של קבלת ההחלטה, החל מהחלטות שנהיה חייבים לקבל ועד החלטות שנקבל רק אם ניתקל במקרה מסויים.

+ +

+ +

if ... else - משפטי אם ... אחרת

+ +

נסתכל על הסוג הנפוץ ביותר של משפטי תנאי ב-JavaScript - משפט התנאי if ... else.

+ +

הסינטקס הבסיסי של משפטי if ... else

+ +

אם ננסה להמחיש את הסינטקס הבסיסי של if...else בצורה מופשטת של {{glossary("pseudocode")}}, הוא ייראה כך:

+ +
if (condition - תנאי) {
+  code to run if condition is true - הקוד שירוץ אם התנאי נכון
+} else {
+  run some other code instead  - הקוד שירוץ אם התנאי לא נכון
+}
+ +

מה שיש לנו כאן זה:

+ +
    +
  1. המילה השמורה if ולאחרי סוגריים רגילות ().
  2. +
  3. לאחר מכן - התנאי שנבדוק האם הוא מתקיים נמצא בתוך ה- () (כמו: ״האם הערך הזה גדול מערך אחר״ או ״הערך הזה קיים״). תנאי זה יעשה שימוש באופרטורים שדבירנו עליהם במודול הקודם - comparison operators אופרטורים להשוואה ויחזיר לנו ערך של אמת - true או ערך של שקר - false.
  4. +
  5. לאחר מכן  - סוגריים מסולסלות - {} - שבתוכן נכניס כל קוד שנרצה, אשר יתבצע אך ורק אם התנאי התקיים, כלומר החזיר תוצאת אמת - true.
  6. +
  7. לאחר מכן - מילה שמורה נוספת שהיא else. אשר באה לבטא מה יקרה, אם בכלל, כאשר התנאי לא יחזיר תוצאת true
  8. +
  9. ולבסוף - סוגריים מסולסלות נוספות{}- שבתוכן נכניס כל קוד שנרצה, אשר יתבצע אך ורק אם התנאי עצמו לא התקיים, כלומר החזיר תוצאת שקר - false.
  10. +
+ +

קוד זה דיי קריא ומובן על ידי בני אדם - הוא אומר בעצם ש-"אם ה- condition (התנאי) מתקיים - כלומר מחזיר ערך של אמת - true, תריץ את קוד A, אחרת - תריץ את קוד B"

+ +

שימו לב שאנחנו לא חייבים את לכלול את ה- else ואת הסוגריים המסולסלות השניות. כך לדוגמא, התנאי הבא הוא חוקי לחלוטין:

+ +
if (condition) {
+  code to run if condition is true
+}
+
+run some other code
+ +

יחד עם זאת, אנחנו צריכים לזכור שבמקרה כזה, הקוד השני שאינו חלק ממשפט התנאי, לא נשלט על ידיו ולא כפוף למשפט התנאי - מה שאומר שהוא ירוץ תמיד לא משנה אם התנאי החזיר ערך true או false. זה לאו דווקא משהו רע, אבל חשוב לדעת זאת.

+ +

לפעמים אנחנו גם נראה משפטי- if...else ללא סוגריים מסולסלות כלל, בקיצור אשר נראה כך:

+ +
if (condition) code to run if condition is true
+else run some other code instead
+ +

זהו קוד תקין לחלוטין, אך אינו מומלץ לשימוש -  הרבה יותר קל לקרוא קוד ולהבין מה קורה, אם אנחנו משתמשים בסוגריים מסולסולת לתחום את הקוד, וכן משתמשים במס׳ שורות ורווחים על מנת להפוך את הקוד לקריא ומובן יותר.

+ +

דוגמא לתרגול

+ +

על מנת להבין את הסינטקס טוב יותר, בוא ננסה דוגמא קטנה לתרגול. דמיינו ילד אשר התבקש לעזור לאימו בביצוע הקניות. אם הוא ישלים את המשימה, הוא יקבל דמי כיס גבוהים יותר מהרגיל:

+ +
var shoppingDone = false;
+
+if (shoppingDone === true) {
+  var childsAllowance = 10;
+} else {
+  var childsAllowance = 5;
+}
+ +

עם זאת, קוד זה תמיד יגרום לכך שהילד יקבל דמי כיס מופחתים שכן בתחילת הקוד המשתנה shoppingDone קיבל את הערך של false. אנחנו צריכים למצוא דרך להפוך את הערך של המשתנה shoppingDone - true אם הילד השלים את הקניות.

+ +
+

תשומת לב: ניתן לראות את הפתרון לתרגול זה ב- GitHub (וכן ניתן לראות אותו כדף אינטרנט.)

+
+ +

else if - משפטי התניה משורשרים

+ +

הדוגמא הקודמת נתנה לנו שתי אפשרויות אך מה אם נצטרך יותר משתי אפשרויות?

+ +

ישנה דרך לשרשר אפשרויות נוספות לתוך משפט if...else שלנו באמצעות שימוש ב- else if. כל בחירה נוספות דורשת בלוק נוסף של קוד שייכנס בין{ ... }() if לבין { ... }else — ראו את הדוגמאות הבאות, שהן בעצם חלק מיישום פשוט לתחזית מזג אוויר:

+ +
<label for="weather">Select the weather type today: </label>
+<select id="weather">
+  <option value="">--Make a choice--</option>
+  <option value="sunny">Sunny</option>
+  <option value="rainy">Rainy</option>
+  <option value="snowing">Snowing</option>
+  <option value="overcast">Overcast</option>
+</select>
+
+<p></p>
+ +
var select = document.querySelector('select');
+var para = document.querySelector('p');
+
+select.addEventListener('change', setWeather);
+
+function setWeather() {
+  var choice = select.value;
+
+  if (choice === 'sunny') {
+    para.textContent = 'It is nice and sunny outside today. Wear shorts! Go to the beach, or the park, and get an ice cream.';
+  } else if (choice === 'rainy') {
+    para.textContent = 'Rain is falling outside; take a rain coat and a brolly, and don\'t stay out for too long.';
+  } else if (choice === 'snowing') {
+    para.textContent = 'The snow is coming down — it is freezing! Best to stay in with a cup of hot chocolate, or go build a snowman.';
+  } else if (choice === 'overcast') {
+    para.textContent = 'It isn\'t raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.';
+  } else {
+    para.textContent = '';
+  }
+}
+
+
+ +

{{ EmbedLiveSample('else_if', '100%', 100, "", "", "hide-codepen-jsfiddle") }}

+ +
    +
  1. כאן יש לנו אלמנט {{htmlelement("select")}} המאפשר לנו לבחור אפשרויות שונות, וכן פסקה פשוטה.
  2. +
  3. ב-JavaScript, אנחו מאחסנים הפניות לאלמנט {{htmlelement("select")}} ולאלמנט- {{htmlelement("p")}} על ידי שמירתם במשתנים ומוסיפים ל-{{htmlelement("select")}} ״מאזין אירוע״ - event listener לאלמנט {{htmlelement("select")}} כך שכאשר הערך שלו ישתנה, הפונקציה ()setWeatherתופעל.
  4. +
  5. כאשר הפונקציה הזו רצה, אנחנו מגדירים תחילה משתנה בשם choice ומשימים לו את הערך הרלוונטי שהמשתמש בחר באלמנט <select>. לאחר מכן, אנחנו משתמשים במשפטי תנאי על מנת לתת כיתוב שונה בטקסט של הפסקאות, בהתאם לערך שיקבל <select> בכל פעם. שימו לב שכל התנאים נבדקים בבלוקי קוד של משפט תנאי {...}()else if, למעט האפשרות הראשונה, אשר נבדק בבלוק של המשפט התנאי {...}()if.
  6. +
  7. האפשרות האחרונה הנמצאת בבלוק של {...}else היא בעצם ברירת המחדל, או האופציה האחרונה. הקוד בבלוק שלה ירוץ רק אם אף אחד מהתנאים לא החזירו true. במקרה הזה, זה ישמש לרוקן את הטקסט מהפסקה ומידה ושום אופציה לא נבחרה.
  8. +
+ +
+

לתשומת לב: אתם גם יכולים למצוא את הדוגמא הזו ב- GitHub או להריץ אותה.

+
+ +

תשומת לב לאופרטורים להשוואה

+ +

אופרטורים להשוואה משמשים לבדוק את התנאים בתוך משפטי התנאי שלנו. עברנו עליהם במאמר מתמטיקה בסיסית ב-JavaScript — מספרים ואופרטורים שלנו. האפשרויות שלנו הן:

+ + + +
+

לתשומת לבכם: חיזרו על החומר אם אינכם זוכרים אותם. 

+
+ +

כאשנו מדברים על תוצאות ההשוואה, אנחנו רוצים לשים תשומת לב לערכים הבוליאנים שנקבל - הלא הם (true/false) ומהו המקור שלהם וכן לשים לב להתנהגות מסויימת שאנחנו ניתקל בה שוב ושוב.

+ +

כל ערך שהוא לא false, undefined, null, 0, NaN, או מחרוזת ריקה - (''), יחזיר לנו אמת - true כאשר הוא נבדק כתנאי במשפט תנאי. ולכן, אנחנו יכולים להשתמש רק בשם של המשתנה בלבד על מנת לבדוק האם הוא אמת או אפילו לבדוק האם הוא קיים - כלומר הוא לא undefined לדוגמא:

+ +
var cheese = 'Cheddar';
+
+if (cheese) {
+  console.log('Yay! Cheese available for making cheese on toast.');
+} else {
+  console.log('No cheese on toast for you today.');
+}
+ +

ואם נחזור לדוגמא הקודמת שלנו עם הילד והמטלה, נוכל לרשום זאת כך:

+ +
var shoppingDone = false;
+
+if (shoppingDone) { // don't need to explicitly specify '=== true'
+  var childsAllowance = 10;
+} else {
+  var childsAllowance = 5;
+}
+ +

שרשור של if ... else

+ +

זה בסדר גמור לשים משפט if...else אחד בתוך השני - כלומר לשרשר אותם. לדוגמא, אנחנו יכולים לעדכן את היישום מזג אוויר שלנו להראות רשימה נוספת של אפשרויות בהתבסס על הטמפרטורה:

+ +
if (choice === 'sunny') {
+  if (temperature < 86) {
+    para.textContent = 'It is ' + temperature + ' degrees outside — nice and sunny. Let\'s go out to the beach, or the park, and get an ice cream.';
+  } else if (temperature >= 86) {
+    para.textContent = 'It is ' + temperature + ' degrees outside — REALLY HOT! If you want to go outside, make sure to put some suncream on.';
+  }
+}
+ +

למרות שכל הקוד עובד יחד, כל משפט if...else עובד לחלוטין באופן עצמאי מהאחר.

+ +

AND, OR או NOT :אופרטוריים לוגיים - Logical operators

+ +

אם נרצה לבדוק מספר תנאים מבלי לשרשר משפטי if...else שונים, logical operators אופרטוריים לוגיים - יכולים לעזור לנו. כשנעשה בהם שימוש בתנאים, השניים ראשונים עושים את הדברים הבאים:

+ + + +

 ניתן היה לרשום את הקוד הקודם באמצעות שימוש באופרטור הלוגי AND בצורה הבאה:

+ +
if (choice === 'sunny' && temperature < 86) {
+  para.textContent = 'It is ' + temperature + ' degrees outside — nice and sunny. Let\'s go out to the beach, or the park, and get an ice cream.';
+} else if (choice === 'sunny' && temperature >= 86) {
+  para.textContent = 'It is ' + temperature + ' degrees outside — REALLY HOT! If you want to go outside, make sure to put some suncream on.';
+}
+ +

בדוגמא זו, הבלוק קוד הראשון ירוץ רק אם 'choice === 'sunny וגם temperature < 86 יחזיר true.

+ +

דוגמא לשימוש באופרטור הלוגי OR:

+ +
if (iceCreamVanOutside || houseStatus === 'on fire') {
+  console.log('You should leave the house quickly.');
+} else {
+  console.log('Probably should just stay in then.');
+}
+ +

הסוג האחרון של אופרטור לוגי - NOT, מבוטא על ידי האופרטור ! וניתן לשימוש על מנת לשלול ביטוי מסויים. נראה אותו בדוגמא הבאה:

+ +
if (!(iceCreamVanOutside || houseStatus === 'on fire')) {
+  console.log('Probably should just stay in then.');
+} else {
+  console.log('You should leave the house quickly.');
+}
+ +

בקוד זה אם ביטוי של OR מסויים מחזיר true, אז האופרטור NOT יהפוך אותו לשלילי על מנת שכל הביטוי יחזור false.

+ +

אנחנו יכולים לאחד כמה משפטי התנייה ואופרטורים לוגיים כמה שנרצה, בכל מבנה שנרצה. הדוגמאות הבאות מריצות קוד בפנים רק אם שני משפטי ה-OR מחזירים ערך של אמת. 

+ +
if ((x === 5 || y > 3 || z <= 10) && (loggedIn || userName === 'Steve')) {
+  // run the code
+}
+ +

טעות נפוצה שעושים כאשר משתמשים באופרטור הלוגי OR במשפט תנאי היא לציין את המשתנה שאנחנו נרצה לבדוק את הערך שלו ואז לתת מס׳ ערכים לבדיקה מופרדים על ידי האופרטור|| (OR) , זה עלול להחזיר לנו ערך של אמת. לדוגמא:

+ +
if (x === 5 || 7 || 10 || 20) {
+  // run my code
+}
+ +

במקרה זה, התנאי בתוך הסוגריים () יחזיר לנו תמיד true, כי המספר 7 או כל מספר שאינו 0, תמיד יחזיר ערך של true כי כל ערך שהוא לא false, undefined, null, 0, NaN, או מחרוזת ריקה - (''), יחזיר לנו אמת - true כאשר הוא נבדק כתנאי במשפט תנאי. 

+ +

על מנת שקוד זה יעבוד לוגית כפי שרצינו, אנחנו צריכים להשתמש אופרטור OR על כל אחד מהם:

+ +
if (x === 5 || x === 7 || x === 10 ||x === 20) {
+  // run my code
+}
+ +

משפטי switch

+ +

משפטי if...else עוזרים לנו לממש קוד מותנה שירוץ בהתאם לתנאים שנגדיר לו, אבל לא בלי החסרונות שלהם. הם לרוב יהיו טובים כאשר יש לנו שתי אפשרויות וכל מהן דורשת כמויות הגיונית של קוד, או כאשר התנאים שלנו מורכבים יחסית. למקרים שבה אנחנו נרצה הרבה מקרים לבדיקה, הקוד עלול להיות קצת מעצבן וארוך. 

+ +

בשביל זה נועדו משפטי switch. משפטים אלו מקבלים ביטוי/ערך בתוך פרמטר ואז בודקים התקיימותו בין מספר אפשרויות שמוגדרות להם. אם הם מוצאים אחת מהאפשרויות שמתאימה לביטוי/ערך שהם קיבלו כפרמטר, הן יריצו את הקוד המתאים. כך זה קורה מבחינה רעיונית:

+ +
switch (expression) {
+  case choice1:
+    run this code
+    break;
+
+  case choice2:
+    run this code instead
+    break;
+
+  // include as many cases as you like
+
+  default:
+    actually, just run this code
+}
+ +

הסבר:

+ +
    +
  1. המילה השמורה switch, ולאחריה סט של סוגריים רגילות ().
  2. +
  3. ביטוי או ערך בתוך הסוגריים.
  4. +
  5. המילה השמורה case, ולאחריה מקרה אפשרי שהביטוי או הערך יכול להיות, לאחריו :.
  6. +
  7. קוד שירוץ אם המקרה מתאים לביטוי/ערך.
  8. +
  9. המילי השמורה break, ולאחריה ; אם האפשרות הקודמת תואמת לערך/ביטוי, הדפדפן יפסיק להריץ את הקוד במשפט ה-switch וימשיך לקוד שמתחת למשפט ה-switch.
  10. +
  11. ניתן להוסיף case כמה שרק נרצה. 
  12. +
  13. לבסוף, המילה השמורה default, ולאחריה : וקוד שירוץ. default תרוץ אם הערך/ביטוי שהוכנס לא תואם לאף אחד מאפשרויות ה-case שרשמנו. במקרה של default - אין צורך להתשמש במילה השמורה break, מכיוון שאין מה להפסיק/לעצור לאחר התקיימותו של מקרה זה. 
  14. +
+ +
+

לתשומת לב:  החלק של default הוא אופציונלי - אנחנו יכולים להשמיט אותו אם אין סיכוי כשהביטוי יחזיר לנו ערך לא ידוע או לא תואם לאף אחד מהמקרים. אם יש סיכוי  כזה - אנחנו צריכים לכלול default במשפט ה-switch על מנת להתמודד עם אותם מקרים לא ידועים. 

+
+ +

דוגמא למשפט switch

+ +

נסתכל על דוגמא אמיתית - נכתוב את יישום מזג האוויר שלנו מחדש באמצעות שימוש במשפט switch:

+ +
<label for="weather">Select the weather type today: </label>
+<select id="weather">
+  <option value="">--Make a choice--</option>
+  <option value="sunny">Sunny</option>
+  <option value="rainy">Rainy</option>
+  <option value="snowing">Snowing</option>
+  <option value="overcast">Overcast</option>
+</select>
+
+<p></p>
+ +
var select = document.querySelector('select');
+var para = document.querySelector('p');
+
+select.addEventListener('change', setWeather);
+
+
+function setWeather() {
+  var choice = select.value;
+
+  switch (choice) {
+    case 'sunny':
+      para.textContent = 'It is nice and sunny outside today. Wear shorts! Go to the beach, or the park, and get an ice cream.';
+      break;
+    case 'rainy':
+      para.textContent = 'Rain is falling outside; take a rain coat and a brolly, and don\'t stay out for too long.';
+      break;
+    case 'snowing':
+      para.textContent = 'The snow is coming down — it is freezing! Best to stay in with a cup of hot chocolate, or go build a snowman.';
+      break;
+    case 'overcast':
+      para.textContent = 'It isn\'t raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.';
+      break;
+    default:
+      para.textContent = '';
+  }
+}
+ +

{{ EmbedLiveSample('A_switch_example', '100%', 100, "", "", "hide-codepen-jsfiddle") }}

+ +
+

לתשומת לבכם: אפשר למצוא את הדוגמא ב-​​​​​GitHub או להריץ אותה פה.

+
+ +

 Ternary operator - אופרטור טרנארי

+ +

סינטקס נוסף שנרצה להציג בפניכם לפני שנמשיך הוא אופרטור טרנארי

+ +

אופרטור טרנארי הוא סינטקס קצר אשר בודק התקיימותו של תנאי מסויים ומבצע פעולה מסויימת אם התנאי מתקיים - true, ופעולה אחרת אם התנאי לא מתקיים - false. אופרטור זה שימושי בסיטואציות מסוימות ויכול לקחת הרבה פחות קוד מאשר if...else, במידה ויש שתי אפשרויות, אשר נבחרות לפי מבחן/תנאי true/false.

+ +

על מנת להפשיט את הנושא, הקוד בצורה רעיונית נראה כך:

+ +
( condition ) ? run this code : run this code instead
+ +

נסתכל על דוגמא פשוטה:

+ +
var greeting = ( isBirthday ) ? 'Happy birthday Mrs. Smith — we hope you have a great day!' : 'Good morning Mrs. Smith.';
+ +

יש לנו פה משתנה בשם isBirthday - אם הוא true, אנחנו נתן הודעת יומולדת שמח, ואם הוא false, אנחנו נתן ברכה רגילה.

+ +

דוגמא לאופרטור טרנארי

+ +

שימו לב כי אנחנו לא חייבים לקבוע ערכים בפרמטרים של האופרטור הטרנארי - אנחנו יכולים גם לתת לו כפרמטרים שורות קוד או פונקציות - כל דבר שנרצה. הדוגמא הבאה מראה לנו אפשרות לבחירת עיצוב לאתר על בסיס אופרטור טרנארי.

+ +
<label for="theme">Select theme: </label>
+<select id="theme">
+  <option value="white">White</option>
+  <option value="black">Black</option>
+</select>
+
+<h1>This is my website</h1>
+ +
var select = document.querySelector('select');
+var html = document.querySelector('html');
+document.body.style.padding = '10px';
+
+function update(bgColor, textColor) {
+  html.style.backgroundColor = bgColor;
+  html.style.color = textColor;
+}
+
+select.onchange = function() {
+  ( select.value === 'black' ) ? update('black','white') : update('white','black');
+}
+
+ +

{{ EmbedLiveSample('Ternary_operator_example', '100%', 300, "", "", "hide-codepen-jsfiddle") }}

+ +

כאן יש לנו אלמנט {{htmlelement('select')}} המאפשר לנו לבחור את הסגנון (שחור או לבן) ובנוסף כותרת פשוטה של {{htmlelement('h1')}} על מנת להציג את הכותרת של האתר. לאחר מכן יש לנו פונקציה שנקראת ()update שמקבלת שני צבעים כארגומנטים. הרקע של האתר נקבע על ידי הצבע הראשון שאנחנו בוחרים, והצבע של הטקסט ניתן כפרמטר השני.

+ +

לבסוף ישלנו ״מאזין אירוע״ - event listener בשם onchange. מאזין אירוע זה מכיל ״מטפל אירוע״ - event handler מסוג מסוג אופרטור טרנארי. הוא מתחיל עם מבחן התנאי - select.value === 'black'. אם התנאי מחזיר true, אנחנו נריץ את פונקציית true עם האפרמטרי ׳black׳ ו-׳white׳ - כלומר אנחנו נקבל רקע שחור עם כיתוב טקסט לבן. אם זה תוצאת התקיימות התנאי היא false - פונקציית ()update תרוץ עם פרמטרים לבן ושחור, כלומר הצבעים יהיו הפוכים.

+ +
+

לתשומת לבכם:  אירועים אלו בעצם פעולות או התרחשויות אשר קורים במערכת, אשר אנחנו יכולים ״להאזין״ להם באמצעות ״מאזין אירוע״ - event listener כך שנוכל להגיב בדרך מסויימת, ברגע שהם יתרחשו באמצעות ״מטפל אירוע״ - event handler. אנו נגע בהם בהמשך.

+
+ +
+

לתשומת לב: ראו גם דוגמא זו ב- GitHub או בדוגמא כדף אינטרנט

+
+ +

למידה עצמאית: לוח שנה פשוט

+ +

בדוגמא הבאה, אנחנו הולכים לכתוב דוגמא ללוח שנה. בקוד שלנו יש:

+ + + +

אנחנו צריכים משפט תנאי בתוך ה-event handler שלנו - כלומר בתוך פונקציית onchange שלנו, מתחת להערה ADD CONDITIONAL HERE //. משפט תנאי זה אמור:

+ +
    +
  1. להסתכל על החודש שנבחר ואוכסן במשתנה choice. זה יהיה הערך של האלמנט <select> לאחר שהערך שלו השתנה. בדוגמא שלנו זה יהיה January.
  2. +
  3. להגדיר משתנה בשם days שיהיה שווה למספר הימים בחודש הנבחר. על מנת לעשות זאת אנחנו נצטרך להסתכל על מספר הימים בכל חודש בשנה. אנחנו יכולים להתעלם משנים מעוברות לצרכי דוגמא זו.
  4. +
+ +

רמזים:

+ + + +

אם אתם עושים טעות - תמיד ניתן לאתחל את הקוד למצבו הראשוני באמצעות כפתור ה-״Reset״. אם ממש נתקעתם - הסתכלו על הפתרון.

+ + + +

{{ EmbedLiveSample('Playable_code', '100%', 1110, "", "", "hide-codepen-jsfiddle") }}

+ +

למידה עצמאית: יותר אפשרויות צבעים!

+ +

בתרגול זה, אנחנו הולכים לקחת את האופרטור הטרנארי שראינו קודם, ולהפוך אותו למשפט switch שיאפשר לנו לבחור מבין אפשרות אחת מבין אפשרויות רבות יותר עבור האתר הפשוט שלנו. הסתכלו על {{htmlelement("select")}} - הפעם אתם תראו שיש לו חמש אופציות ולא שתיים. אתם נדרשים להוסיף משפט switch ישר מתחת להערת ADD SWITCH STATEMENT //אשר יבצע את הפעולות הבאות:

+ + + +

אם אתם עושים טעות - תמיד ניתן לאתחל את הקוד למצבו הראשוני באמצעות כפתור ה-״Reset״. אם ממש נתקעתם - הסתכלו על הפתרון.

+ + + +

{{ EmbedLiveSample('Playable_code_2', '100%', 950, "", "", "hide-codepen-jsfiddle") }}

+ +

לסיכום

+ +

אלו הדברם העיקריים והמרכזיים שאנחנו צריכים לדעת על משפטי תנאי ומבניהם ב-JavaScript. אם לא הבנתם את הרעיונות שעברנו עליהם בתרגולים למעלה, חזרו על השיעור שוב. ואם משהו לא ברור, צרו עמנו קשר לשם קבלת עזרה.

+ +

ראו גם

+ + + +

{{NextMenu("Learn/JavaScript/Building_blocks/Looping_code", "Learn/JavaScript/Building_blocks")}}

+ +

במודול זה

+ + diff --git a/files/he/learn/javascript/first_steps/a_first_splash/index.html b/files/he/learn/javascript/first_steps/a_first_splash/index.html new file mode 100644 index 0000000000..76a5d40f9b --- /dev/null +++ b/files/he/learn/javascript/first_steps/a_first_splash/index.html @@ -0,0 +1,634 @@ +--- +title: מבט ראשון ל-JavaScript +slug: Learn/JavaScript/First_steps/A_first_splash +translation_of: Learn/JavaScript/First_steps/A_first_splash +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/First_steps/What_is_JavaScript", "Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps")}}
+ +

עכשיו כשלמדתם קצת על התיאוריה של JavaScript, אנחנו יכולים להיכנס לעומק יותר ולצדדים הפרקטיים. אנחנו נבנה יחד משחק ״נחש את המספר״, צעד אחד צעד. 

+ + + + + + + + + + + + +
ידע מוקדם:הבנה בסיסית של מחשב, הבנה בסיסית של  HTML, CSS ו - JavaScript.
מטרה:להתנסות בכתיבת קוד JavaScript ולהבין כיצד לנסות לעשות זאת.
+ +

אנו לא מצפים שתבינו את כל הקוד לפרטי פרטים ישר על ההתחלה. אנחנו רק רוצים להציג לכם בצורה עקרונית את הרעיון כיצד השפה עובדת. בהמשך המאמרים ניכנס יותר לעומק. 

+ +
+

הרבה מהמאפיינים והאפשרויות ב-JavaScript זהים לשפות תכנות אחרות - כמו לדוגמא לולאות, פונקציות וכד׳. הסינטקס אולי שונה, אבל הרעיונות בגדול דומים.

+
+ +

לחשוב כמו מתכנת או מתכנתת

+ +

אחד מהדברים הקשים ללמידה בפיתוח תוכנה אינו למידת השפה או הסינטקס, אלא איך אנחנו מחילים את השפה לפתרון בעיות אמיתיות. אנחנו צריכים להתחיל לחשוב כמו מתכנתים - זה בעצם כולל בתוכו התבוננות על התיאור של מה התוכנית שלנו צריכה לעשות, להבין מה מאפייני הקוד שאנחנו צריכים כדי להשיג את אותם דברים ואיך אנחנו גורמים להם לעבוד יחד. 

+ +

זה דורש מאיתנו שילוב של עבודה קשה, ניסיון עם סינטקס השפה, תרגול, וכן מעט יצירותיות. ככל שנכתוב קוד יותר, ככה נשתפר בכך. אנחנו לא יכולים להבטיח שנגרום לך לפתח ״מוח של מתכנת״ בחמש דקות, אבל אנחנו נתן לך את מירב ההזדמניות לתרגל חשיבה של מתכנת בקורס זה.

+ +

דוגמא — משחק ״נחש את המספר״

+ +

במאמר זה אנחנו נראה לך כיצד ליצור משחק פשוט:

+ + + +

{{ EmbedLiveSample('Top_hidden_code', '100%', 320, "", "", "hide-codepen-jsfiddle") }}

+ +

נסו לשחק עם הקוד קצת, הכירו את המשחק לפני שאתם ממשיכים הלאה.

+ +

תדמיינו שהבוס שלכם נתן את התיאור הקצר ליצירת המשחק הזה:

+ +
+

הבוס: ״אני רוצה שתצרו משחק פשוט של ״נחש את המספר״. 

+ +

הוא אמור ליצור מספר בין 1 ל-100, כאשר המשתתף צריך לנחש את המספר בכפולות של 10. 

+ +

אחרי כל פעם שהמשתתף ניחש את המספר, המשחק יגיד לו אם הוא טעה או צדק, אם הוא טעה, הוא יגיד לו האם הניחוש היה גבוה מדי או נמוך מדיץ בנוסף, המשחק צריך להגיד למשתתף כמה ניחושים הוא ביצע כבר. המשחק יסתיים ברגע שהמשתתף ינחש נכונה את המספר האקראי או ברגע שנגמרו לו הנסיונות. כשהמשחק הסתיים, המשתמש צריך לקבל אפשרות להתחיל את המשחק מחדש. 

+
+ +

עכשיו, ננסה להפוך את למשימות פשוטות, בצורה מתוכננת כמה שאפשר: 

+ +
    +
  1. צור מספר בין 1 ל-100.
  2. +
  3. שמור את הניסיון של המשתתף. תתחיל במספר 1 שכן זהו הניסיון הראשון.
  4. +
  5. ספק למשתמש דרך לנחש את המספר האקראי.
  6. +
  7. ברגע שהמתשמש ניחש, שמור את הניחוש שלו כדי שתוכל להציג לו את הניחושים הקודמים.
  8. +
  9. בדוק האם המשתמש ניחש את המספר האקראי.
  10. +
  11. אם ניחש נכונה: +
      +
    1. הצג הודעת זכייה. 
    2. +
    3. תמנע מהמשתמש להזין ניחושים נוספים.
    4. +
    5. תציג למשתמש אפשרות לאתחל את המשחק.
    6. +
    +
  12. +
  13. אם המשתמש לא ניחש נכונה ונותרו לו הנסיונות : +
      +
    1. תציג למשתמש שהוא טעה.
    2. +
    3. תאפשר לו לנחש שוב.
    4. +
    5. תעלה את מספר הנסיונות שלו ב-1.
    6. +
    +
  14. +
  15. אם המשתמש לא ניחש נכונה ונגמרו לו הנסיונות: +
      +
    1. תציג למשתמש שהמשחק נגמר.
    2. +
    3. תמנע מהמשתמש להזין ניחושים נוספים.
    4. +
    5. תציג למשתמש אפשרות לאתחל את המשחק.
    6. +
    +
  16. +
  17. ברגע שהמשחק אותחל מחדש, תוודא שהלוגיקה והנראות של המשחק מאותחלים לחלוטין וחזור לצעד מספר 1.
  18. +
+ +

כעת נראה כיצד ניתן להפוך את רשימת המשימות הזו לקוד של JavaScript.

+ +

הגדרות ראשונות

+ +

על מנת להתחיל את המדריך, צרו עותק מקומי של הקובץ number-guessing-game-start.html או ראו כדף אינטרנט.

+ +

פתחו אותו גם בעורך הקוד וגם בדפדפן. בנקודה זו אתם תראו כותרת, פסקת הוראות וטופס להכניס ניחוש, אבל הטופס לא עובד כראוי. 

+ +

אנחנו נכניס את הקוד שלנו בתוך האלמנט {{htmlelement("script")}} בתחתית קובץ ה-HTML:

+ +
<script>
+
+  // Your JavaScript goes here
+
+</script>
+
+ +

הוספת משתנים לשם אחסון המידע

+ +

ראשית, הכניסו את השורות הבאות תוך האלמנט {{htmlelement("script")}} :

+ +
let randomNumber = Math.floor(Math.random() * 100) + 1;
+
+const guesses = document.querySelector('.guesses');
+const lastResult = document.querySelector('.lastResult');
+const lowOrHi = document.querySelector('.lowOrHi');
+
+const guessSubmit = document.querySelector('.guessSubmit');
+const guessField = document.querySelector('.guessField');
+
+let guessCount = 1;
+let resetButton;
+ +

חלק זה של הקוד מגדיר משתנים וקבועים שאנחנו צריכים על מנת לאחסן את המידע שהתוכנית שלנו תצטרך. משתנים הם בעצם כמו קופסאות אחסון עבור ערכים מסוגים שונים אשר יכולים להיות מספרים, טקסט, אובייקטים, מערכים וכד׳. 

+ +

אנו יוצרים משתנה באמצעות שימוש במילה שמורה של JavaScript בשם letאו var ולאחר מכן בשם שאנחנו רוצים להעניק למשתנה שלנו. (אנחנו נלמד על ההבדלים ביניהם במאמר בהמשך).

+ +

קבועים לעומת זאת, אלו מעין קופסאות אחסון שנועדו לאחסן ערכים שאנחנו לא נרצה לשנות, ואותם אנחנו יוצרים באמצעות מילה שמורה בשם  const. במקרה שלנו אנחנו משתמשים בקבועים על מנת לאחסן את ההפניות לאלמנטים בדף ה-html, כלומר לממשק המשתמש. אמנם יכול להיות שהתוכן שלהם ישתנה, אבל ההפניה לאותו אלמנט תישאר קבועה לאורך התוכנית.

+ +

על מנת לשים ערך מסויים במשתנה או בקבוע מסויים, אנחנו משתמשים בסימן ״שווה״ (=), ולאחר מכן הערך שאנחנו רוצים להשים באותו משתנה או קבוע.

+ +

בדוגמא שלנו :

+ + + +
+

לתשומת לב: אתם תלמדו עוד על משתנים וקבועים בהמשך הקורס, החל מהמאמר הבא.

+
+ +

פונקציות

+ +

הוסיפו את הקוד הבא, מתחת לקוד הקיים שלכם:

+ +
function checkGuess() {
+  alert('I am a placeholder');
+}
+ +

פונקציות הם בעצם חלקי קוד הניתנים לשימוש חוזר, אותם ניתן לרשום פעם אחת, ולהריץ שוב ושוב. זה מאוד שימושי. יש כמה דרכים להגדיר פונקציה אבל כעת אנחנו נתמקד בצורה פשוטה אחת. 

+ +

כאן אנחנו הגדרנו את הפונקציה באמצעות שימוש במילה שמורה function ולאחר מכן שם הפונקציה וסוגריים (). לאחר מכן, הוספנו סוגריים מסולסלים {}. כל מה שנמצא בתוך הסוגריים המסולסלים זה הקוד שנרצה שירוץ בכל פעם שנקרא לפונקציה. 

+ +

כשנרצה להריץ את הקוד, אנחנו פשוט נקליד את שם הפונקציה ובצמוד לה נשים סוגריים (). שמרו את הקובץ ורענן את הדף בדפדפן. לאחר מכן, הזן בקונסולה, את השורה הבאה:  

+ +
checkGuess();
+ +

לאחר שנלחץ על  Return/Enter, אנחנו אמורים לראות שקפצה הודעה שרשמה "I am a placeholder".

+ +

הגדרנו פונקציה שמקפיצה הודעה למשתמש בכל פעם שנקרא לה.

+ +
+

לתשומת לב: אתם תלמדו עוד על פונקציות בהמשך הקורס.

+
+ +

אופרטורים (Operators)

+ +

אופרטורים של JavaScript מאפשרים לנו לבצע מבחנים מסויימים, חישובים מתמטיים, חיבור מחרוזות ודברים נוספים רבים. 

+ +

אם לא עשיתם זאת עד עכשיו, שמרו את הקוד, ורעננו את הדף. לאחר מכן, פתחו את הקונסולה. נסו להזין את הדוגמאות המפורטות למטה בעמודת ״דוגמא״, בדיוק בצורה שבה הן מופיעות ולאחר מכן לחצו Return/Enter  וראו את התוצאות. 

+ +

נתחיל עם אופרטורים מתמטיים:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
אופרטורשםדוגמא
+חיבור6 + 9
-חיסור20 - 15
*כפל3 * 7
/חילוק10 / 5
+ +

ניתן להשתמש בסימן החיבור + על מנת לחבר מחרוזות ביחד (בתכנות, בשפה האנגלית זה נקרא: concatenation).

+ +

נסו להזין את השורות הבאות בקונסולה, אחת בכל פעם:

+ +
let name = 'Bingo';
+name;
+let hello = ' says hello!';
+hello;
+let greeting = name + hello;
+greeting;
+ +

יש גם כמה קיצורים לאופרטורים מתמטיים, לדוגמא, אם אנחנו פשוט רוצים להוסיף מחרוזת טקסט חדשה למחרוזת טקסט קיימת ולהחזיר את המחרוזת המחוברת של שתיהן, נוכל לבצע את הדבר הבא: 

+ +
name += ' says hello!';
+ +

זה זהה בתוצאה לדבר הבא:

+ +
name = name + ' says hello!';
+ +

כשאנחנו מריצים מבחני אמת/שקר (לדוגמא, בתוך תנאים), אנחנו משתמשים באופרטורים השוואתיים

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
אופרטורשםדוגמא
===האם זהה לחלוטין? +
+5 === 2 + 4 // false
+'Chris' === 'Bob' // false
+5 === 2 + 3 // true
+2 === '2' // false; number versus string
+
+
!==האם לא זהה? +
+5 !== 2 + 4 // true
+'Chris' !== 'Bob' // true
+5 !== 2 + 3 // false
+2 !== '2' // true; number versus string
+
+
<קטן מ- +
+6 < 10 // true
+20 < 10 // false
+
>גדול מ- +
+6 > 10 // false
+20 > 10  // true
+
+ +

משפטי תנאי

+ +

נחזור לפונקציית  ()checkGuess שלנו. אנחנו נרצה שהיא תעשה יותר מאשר להוציא הודעה פשוטה למשתמש. אנחנו רוצים לבדוק האם הניחוש של המשתמש היה נכון או לא  ולהגיב ובהתאם. 

+ +

 בנקודה זו, החלף את הפונקציה ()checkGuess עם הקוד הבא: 

+ +
function checkGuess() {
+  let userGuess = Number(guessField.value);
+  if (guessCount === 1) {
+    guesses.textContent = 'Previous guesses: ';
+  }
+  guesses.textContent += userGuess + ' ';
+
+  if (userGuess === randomNumber) {
+    lastResult.textContent = 'Congratulations! You got it right!';
+    lastResult.style.backgroundColor = 'green';
+    lowOrHi.textContent = '';
+    setGameOver();
+  } else if (guessCount === 10) {
+    lastResult.textContent = '!!!GAME OVER!!!';
+    setGameOver();
+  } else {
+    lastResult.textContent = 'Wrong!';
+    lastResult.style.backgroundColor = 'red';
+    if(userGuess < randomNumber) {
+      lowOrHi.textContent = 'Last guess was too low!';
+    } else if(userGuess > randomNumber) {
+      lowOrHi.textContent = 'Last guess was too high!';
+    }
+  }
+
+  guessCount++;
+  guessField.value = '';
+  guessField.focus();
+}
+ +

נעבור על כל חלק בקוד על מנת להסביר אותו: 

+ + + +

אירועים

+ +

בשלב זה הגדרנו את פונקציית ()checkGuess אבל היא לא תעשה כלום כי לא קראנו לה עדיין. באופן אידיאלי, אנחנו רוצים ״לקרוא״ (Invoke) לפונקציה כאשר המשתמש ילחץ על לחצן ״Submit guess" ועל מנת לבצע זאת אנחנו צריכים לעשות שימוש באירוע (Event). אירועים אלו דברים המתרחשים בתוך הדפדפן - כפתור נלחץ, דף נטען, וידאו מתנגן וכד׳ - ובהתאם, אנחנו יכולים להריץ בלוקים של קוד. הקונסטרקטור (בעברית: הבנאי), שמאזין לאותו אירוע שמתרחש בדפדפן נקרא מאזין אירוע (event listeners), ואילו בלוק הקוד שרץ בתגובה לאותו אירוע נקרא מטפל אירוע (event handlers).

+ +

הוסף את הקוד הבא מתחת לפונקציית ()checkGuess :

+ +
guessSubmit.addEventListener('click', checkGuess);
+ +

כאן אנו מוסיפים event listener לכפתור guessSubmit. מתודה זו מקבלת 2 ערכים (שנקראים ״ארגומנטים״) - הראשון הוא סוג האירוע שאנחנו רוצים להאזין לו (במקרה, אירוע מסוג  click), ואותו נזין כמחרוזת, עטוף בגרשיים, לאחר מכן פסיק, ואז את event handlers, שהוא בעצם הקוד שנרצה שירוץ ברגע שהתרחש האירוע (במקרה זה, פונקציית ()checkGuess ). תשומת לב כי אנחנו לא צריכים להכניס סוגריים כאשר אנחנו רושמים את הפונקציה checkGuess בתוך המתודה {{domxref("EventTarget.addEventListener", "addEventListener()")}}.

+ +

נסו לשמור ולרען את הדף כעת - הדוגמא אמורה לעבוד, עד נקודה מסויימת. הבעיה היחידה היא שכאשר המשתתף ינחש נכון או המשחק הסתיים כי נגמרו לו הנסיונות, המשחק יסתיים בצורה לא רצויה, מכיוון שלא הגדרנו את הפונקציה ()setGameOver שאמורה לרוץ ברגע שהמשחק יסתיים (הן אם המשתתף ניחש נכון והן אם למשתתף נגמרו הנסיונות).

+ +

כעת נוסיף את הקוד החסר ונשלים את הפונקציונליות של המשחק.  

+ +

השלמת הפונקציונליות של המשחק

+ +

כעת נוסיף את הפונקציה ()setGameOver מתחת לקוד הנוכחי: 

+ +
function setGameOver() {
+  guessField.disabled = true;
+  guessSubmit.disabled = true;
+  resetButton = document.createElement('button');
+  resetButton.textContent = 'Start new game';
+  document.body.appendChild(resetButton);
+  resetButton.addEventListener('click', resetGame);
+}
+ + + +

עת אנחנו צריכים להגדיר את הפונקציה הזו. הוסף את הקוד הבא מתחת לקוד הנוכחי: 

+ +
function resetGame() {
+  guessCount = 1;
+
+  const resetParas = document.querySelectorAll('.resultParas p');
+  for (let i = 0 ; i < resetParas.length ; i++) {
+    resetParas[i].textContent = '';
+  }
+
+  resetButton.parentNode.removeChild(resetButton);
+
+  guessField.disabled = false;
+  guessSubmit.disabled = false;
+  guessField.value = '';
+  guessField.focus();
+
+  lastResult.style.backgroundColor = 'white';
+
+  randomNumber = Math.floor(Math.random() * 100) + 1;
+}
+ +

קוד זה מאתחל הכל לאיך שהוא היה בתחילת המשחק: 

+ + + +

בשלב זה - יש לנו משחק שעובד במלואו. פשוט יחסית, אך עובד.  

+ +

כעת נדבר על אפשרויות נוספות שראינו, ואולי לא שמנו לב. 

+ +

לולאות

+ +

חלק מתוך הקוד למעלה שנרצה להתעמק בו הוא לולאת מסוג for.

+ +

לולאות הן עקרון מאוד חשוב בתכנות, ומאפשרות לנו להריץ קוד שוב ושוב, עד שתנאי מסויים יתרחש. 

+ +

על מנת להתחיל, פתח את הקונסולה שוב, והכנס את הקוד הבא: 

+ +
for (let i = 1 ; i < 21 ; i++) { console.log(i) }
+ +

מה קרה?

+ +

המספרים 1 עד 20 הודפסו לקונסולה. זה מכיוון שהשתמשנו בלולאה מסוג for. לולאה מסוג for מקבלת 3 ערכים (ארגומנטים):

+ +
    +
  1. ערך ראשון (Starting Value) - במקרה זה אתחלנו את המונה ל-1, אך אנו יכולים להתחיל בכל מספר שנרצה. כמו כן, את שם המשתנה i ניתן להחליף בכל שם שנרצה. אנו מבצעים שימוש ב-i כי זה קצר ונוח לזכור. 
  2. +
  3. תנאי יציאה (An exit condition) - כאן הגדרנו שתנאי היציאה מהלולאה, כלומר מתי הלולאה תפסיק לרוץ יהיה כל עוד i < 21. כלומר הלולאה תרוץ כל זמן ש-i יהיה קטן מ-21. ברגע ש-i יהיה שווה ל-21, הלולאה תפסיק לרוץ.
  4. +
  5. המוסיף (An incrementor) - כאן הגדרנו i++ כלומר נעלה את הערך של i  ב-1 בכל פעם שהקוד שנמצא בתוך הסוגריים המסולסלות {} מסיים לרוץ (כל איטרציה-iteration), עד אשר i יגיע לערך 21. במקרה הזה אנחנו פשוט מדפיסים לקונסולה את הערך של i בכל איטרציה (iteration), באמצעות {{domxref("Console.log", "console.log()")}}.
  6. +
+ +

בוא נסתכל כעת על הלולאה במשחק הניחוש שבנינו בתוך פונקציית ()resetGame:

+ +
let resetParas = document.querySelectorAll('.resultParas p');
+for (let i = 0 ; i < resetParas.length ; i++) {
+  resetParas[i].textContent = '';
+}
+ +

קוד זה יוצר משתנה מסוג מערך (נדבר עליו בהמשך) בשם resetParas המכיל רשימה של כל האלמנטים מסוג p הנמצאים בתוך אלמנט עם class בשם resultParas (במקרה שלנו זה האלמנט הבא: <div class="resultParas">). 

+ +

resetParas נוצר באמצעות שימוש במתודה {{domxref("Document.querySelectorAll", "querySelectorAll()")}}. 

+ +

לאחר מכן, הוא עובר באמצעות לולאה על כל איבר במערך, ומסיר את התוכן טקסט של כל איבר. 

+ +

דיון קצר על אובייקטים

+ +

נוסיף שיפור נוסף לפני שנמשיך בדיון : הוסיפו את הקוד הבא, מתחת לקוד זה: let resetButton; הנמצא בראש הדף, ולאחר מכן שמרו את הקובץ: 

+ +
guessField.focus();
+ +

קוד זה עושה שימוש במתודה בשם {{domxref("HTMLElement.focus", "focus()")}} על מנת לשים את סמן העבר בתוך הטקסט של תיבת הקלט {{htmlelement("input")}} ברגע שהדף נטען, כך שהמשתמש יוכל הזין את הניחוש הראשון שלו ישר כשהדף נטען, ללא צורך ללחוץ על תיבת הקלט. זוהי אמנם תוספת קטנה, אך היא משפרת השימוש של המשתמש ומאפשרת לו להבין באופן ויזואלי איך לשחק את המשחק.

+ +

נכנס לזה קצת יותר לעומק. ב-JavaScript, כל דבר הוא אובייקט. אובייקט הוא אוסף של מס׳ פונקציונליות וערכים אשר קובצו יחד לקבוצה אחת. אנו יכולים ליצור אובייקט בעצמו, אך נגע בנושא זה בהמשך. לצורך העניין במאמר הנוכחי, אנחנו נדון בקצרה באובייקטים המובנים בדפדפן, אשר מאפשרים לנו לעשות הרבה דברים שימושיים. 

+ +

במקרה הנוכחי, יצרנו תחילה קבוע בשם guessField אשר אחסן בתוכן הפנייה לתיבת קלט הטקסט ב-html - השורה הבאה יכולה להימצא באזור שבו הצרנו על המשתנים/קבועים בתחילת הקוד שלנו: 

+ +
const guessField = document.querySelector('.guessField');
+ +

על מנת לקבל את ההפניה הזו, השתמשנו במתודה  {{domxref("document.querySelector", "querySelector()")}} של האובייקט {{domxref("document")}}. דוגמא נוספת היא למתודה של אובייקט זה היא  ()querySelector אשר מקבלת מידע אחד מסוג סלקטור של CSS - ואותו סלקטור בוחר את האלמנט שאנחנו רוצים להפנות אליו. 

+ +

מכיוון ש-guessField מכיל כעת הפנייה לאלמנט {{htmlelement("input")}}, הוא יכול כעת לגשת למספר מאפיינים (properties) ומתודות (methods). באופן עקרוני, properties אלו משתנים המאוחסנים בתוך אובייקט, וחלקם לא יכולים לשנות את ערכם, ואילו methods אלו פונקציות המאוחסנות בתוך אובייקט. מתודה אחת אשר זמינה לאלמנט {{htmlelement("input")}}, היא ()focus, כך שאנחנו יכולים להשתמש בקוד למטה, על מנת לבצע פוקוס לתיבת קלט הטקסט: 

+ +
guessField.focus();
+ +

משתנים שאינם כוללים הפנייה לאלמנטים של טפסים, אינם יכולים לגשת למתודה הזו והיא לא תהיה זמינה עבורם. לדוגמא, הקבוע guesses מכיל הפנייה לאלמנט  {{htmlelement("p")}} ו-המשתנה guessCount מכיל מספר. 

+ +

לשחק ולנסות את האובייקטים של הדפדפן

+ +

בואו נשחק טיפה עם האובייקטים של הדפדפן.

+ +
    +
  1. פתחו תוכנית בדפדפן.
  2. +
  3. פתחו את browser developer tools ווודאו שהקונסולה מופיעה. 
  4. +
  5. רשמו guessField והקונסולה תציג לכם את המשתנה המכיל את האלמנט {{htmlelement("input")}}. אתם תבחינו שהקונסולה גם משלימה את השמות של האובייקטים שקיימים בסביבת ההרצה, כולל משתנה. 
  6. +
  7. כעת הזינו את הקוד הבא: 
  8. +
  9. +
    guessField.value = 'Hello';
    + המאפיין (property) בשם value מייצג את הערך שהוזן לתוך שדה הטקסט. ניתן לראות שעם הזנת הקוד לעיל, אנחנו משנים את הטקסט בשדה הטקסט. 
  10. +
  11. נסו לרשום בקונסולה guesses. הקונסולה תראה לכם שהוא מכיל אלמנט מסוג{{htmlelement("p")}}.
  12. +
  13. כעת הזן את הקוד הבא:
  14. +
  15. +
    guesses.value
    + הקונסולה תחזיר את הערך undefined מכיוון שאלמנט מסוג {{htmlelement("p")}} לא מקבל מאפיין מסוג value.
  16. +
  17. על מנת לשנות את הטקסט בתוך {{htmlelement("p")}} , אנחנו צריכים להשתמש במאפיין בשם  {{domxref("Node.textContent", "textContent")}}
  18. +
  19. כעת הזינו את הקוד הבא:
  20. +
  21. +
    guesses.textContent = 'Where is my paragraph?';
    +
  22. +
  23. כעת ננסה לשנות עיצוב באמצעות גישה ל-properties של האובייקט: +
    guesses.style.backgroundColor = 'yellow';
    +guesses.style.fontSize = '200%';
    +guesses.style.padding = '10px';
    +guesses.style.boxShadow = '3px 3px 6px black';
    + כל אלמנט שנמצא בדף מכיל מאפיין בשם style אשר הוא בעצמו אובייקט המכיל את כללי ה-CSS ה-inline שהוחלו על אותו אובייקט (ואף ניתן להחיל עליו כללי CSS או למחוק את הכללים הנוכחיים או להחליפם באחרים) . זה מאפשר לנו לשנות באופן דינמי את העיצוב של האובייקט באמצעות JavaScript.
  24. +
+ +

לסיכום

+ +

סיימנו לבנות את הדוגמא. בדקו את הקוד הסופי שלכם וודאו שהוא עובד כראוי, או שתוכלו לשחק עם הגרסה הסופית פה אם אתם לא מצליחים לגרום לקוד שלכם לעבוד, נסו להשוות אותו אל מול קוד המקור

+ +

{{PreviousMenuNext("Learn/JavaScript/First_steps/What_is_JavaScript", "Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps")}}

+ +

במודול זה

+ + diff --git a/files/he/learn/javascript/first_steps/arrays/index.html b/files/he/learn/javascript/first_steps/arrays/index.html new file mode 100644 index 0000000000..44675349fa --- /dev/null +++ b/files/he/learn/javascript/first_steps/arrays/index.html @@ -0,0 +1,564 @@ +--- +title: Arrays - מערכים +slug: Learn/JavaScript/First_steps/Arrays +translation_of: Learn/JavaScript/First_steps/Arrays +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps/Silly_story_generator", "Learn/JavaScript/First_steps")}}
+ +

במאמר האחרון במודול זה, אנחנו נדע במערכים - דרך מסודרת וקלה לאחסן רשימה פריטי מידע תחת משתנה אחד. אנחנו נבין מדוע שמוש במערך הוא שימושי כל כך ונבין כיצד ליצור מערך, לשנות את האיברים שלו, למחוק או להוסיף לו איברים ועוד.

+ + + + + + + + + + + + +
ידע מוקדם:הבנה בסיסית של מחשב, הבנה בסיסית של HTML, CSS ו - JavaScript.
Objective:הבנה של מערכים וביצוע פעולות שונות עליהם
+ +

מה זה בעצם מערך - Array?

+ +

מערכים לרוב מתוארים כאובייקט של מעין רשימה (״list-like objects״). בעיקרון, אלו אובייקטים המכילים מספר ערכים שמאוחסנים יחד.

+ +

אובייקטים מסוג מערך יכולים להיות מאוחסנים בתוך משתנה ונוכל לטפל בהם בדיוק כמו שאנחנו מטפלים במשתנים אחרים.

+ +

אנו יכולים לטפל בכל ערך בודד באותו במערך או במערך בכללותו. אנחנו יכולים לעבור על כל איברי המערך אחד אחרי השני ולבצע בהם פעולות שונות. כך לדוגמא, אם יש לנו סדרה של מוצרים והמחירים שלהם מאוחסנים במערך, אנחנו רוצים לעבור על כל המחירים ולהדפיס אותם בחשבונית, ובמקביל לחשב את הסכום הכולל של המוצרים יחד עם המחירים שלהם.

+ +

אם לא היו לנו מערכים, היינו צריכים לשמור כל פריט במשתנה אחר, ואז לכתוב קוד שידפיס את המחיר בנפרד עבור כל משתנה. זה היה הופך את הקוד שלנו להרבה יותר מורכב וארוך ופחות יעיל. אם היו לנו 10 פריטי להדפיס לחשבונית זה עוד נשמע הגיוני, אך מה נעשה במצב שיש לנו 100 פריטים או 1,000 פריטים? נחזור לדוגמא זו בהמשך המאמר על מנת להבין כיצד ניתן לעשות זאת.

+ +

כמו במאמרים קודמים, אנחנו נלמד על הבסיס של מערכים באמצעות שימוש בקונסולה.

+ +

יצירת מערכים

+ +

מערכים כוללים סוגריים מרובעות [] וכל איבר (אלמנט) במערך מופרד מאיבר אחר על ידי פסיק ,.

+ +
    +
  1. נניח ואנחנו רוצים לאחסן רשימת פריטים בתוך מערך. הכניסו את הקוד הבא לקונסולה: +
    let shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles'];
    +shopping;
    +
  2. +
  3. בדוגמא למעלה, כל איבר הוא מחרוזת, אך ניתן לאחסן כל מיני סוגי ערכים בתוך מערכים - מחרוזות, מספרים, אובייקטים ואפילו מערכים נוספים. לדוגמא: +
    let sequence = [1, 1, 2, 3, 5, 8, 13];
    +let random = ['tree', 795, [0, 1, 2]];
    +
  4. +
  5. לפני שתמשיכו, נסו ליצור מספר מערכים וחקרו את האפשרויות השונות.
  6. +
+ +

גישה לאיברי המערך ושינוי שלהם

+ +

אנחנו יכולים לגשת לכל איבר במערך על ידי שימוש בסוגריים המרובעות [] בדיוק כפי שאנו ניגשים לתווים במחרוזת.

+ +
    +
  1. הכניסו את הקוד הבא לקונסולה: +
    shopping[0];
    +// returns "bread"
    +
  2. +
  3. אנחנו גם יכולים לשנות איבר במערך באמצעות מתן ערך חדש לאותו איבר במערך. ראו לדוגמא: +
    shopping[0] = 'tahini';
    +shopping;
    +// shopping will now return [ "tahini", "milk", "cheese", "hummus", "noodles" ]
    + +
    להזכירכם: מחשבים מתחילים לספור מ-0 ולא מ-1. בדיוק כמו במחרוזות, כך גם במערכים.
    +
  4. +
  5. שימו לב שמערך בתוך מערך נקרא מערך רב מימדי. אנחנו יכולים לגשת לאיבר שנמצא בתוך מערך מסויים, כאשר המערך הזה נמצא בתוך מערך באמצעות שרשור של שתי סוגריים מרובעות ביחד. לדוגמא, על מנת לגשת לאיבר במערך שהוא האיבר השלישי במערך המשורשר והמערך המשורשר הוא האיבר השלישי במערך הראשי בשם random, אנו נצטרך לרשום זאת בצורה הבאה: +
    random[2][2];
    +
  6. +
  7. נסו לעשות כמה פעולות ושינויים בעצמכם על מנת להבין את הדרך שבה אנו ניגשים לאיברים במערך.
  8. +
+ +

מציאת האורך של מערך

+ +

מציאת האורך של מערך - כלומר כמה איברים יש לו - מתבצעת בדיוק באותה דרך שבה אנחנו מוצאים את מספר התווים במחרוזת - באמצעות המאפיין {{jsxref("Array.prototype.length","length")}}.

+ +

נסו להזין את הקוד הבא:

+ +
sequence.length;
+// should return 7
+ +

מאפיין length  גם ישמש אותנו לצורך מעבר על איברי המערך באמצעות לולאת for וביצוע פעולות כלשהן שנבחר על כל איבר ואיבר, כך שהלולאה תעבור על כל איברי המערך. לדוגמא:

+ +
let sequence = [1, 1, 2, 3, 5, 8, 13];
+for (let i = 0; i < sequence.length; i++) {
+  console.log(sequence[i]);
+}
+ +

אנחנו נלמד יותר לעומק על לולאות במאמרים הבאים, אך בהסבר פשוט, הקוד הנוכחי אומר את הדברים הבאים:

+ +
    +
  1. הרצת הקוד שנמצא בין הסוגריים המסולסלות {} על כל איבר במערך החל מהאיבר הראשון במערך (אשר נמצא במיקום 0 כמובן). את מספר המיקום של האיבר במערך אותו אנו מייצגים באמצעות המשתנה i.
  2. +
  3. הרצת הלולאה מסוג for כל עוד מיקומו של האיבר במערך (שכאמור מיוצג בכל ריצה על ידי המשתנה i) קטן מסך כל האיברים במערך. כלומר, במקרה זה הקוד בתוך הסוגריים המסולסלות {} לא ירוץ כאשר המשתנה i יהיה שווה ל-7. (להזכירכם - אמנם יש שבעה איברים במערך, אך הספירה שלהם מתחילה ב-0, ולכן האיבר השביעי במערך, יהיה במיקום/אינדקס השישי וזו הסיבה שהשתמשנו בסימן קטן מאורך המערך (>) ולא שווה לאורך המערך (=) שכן אז היינו מקבלים במיקום השביעי את הערך undefiened.
  4. +
  5. בתוך הסוגריים המסולסלות, רשמנו את הקוד שאנחנו רוצים שיבוצע במסגרת כל ריצה של הלולאה. במקרה הזה, הדפסנו לקונסולה את הערך הנוכחי של האיבר שעליו רצה הלולאה באותה ריצה. לצורך הדפסה לקונסולה עשינו שימוש ב-()console.log.
  6. +
+ +

מס׳ מתודות שימושיות של מערכים

+ +

בחלק זה אנחנו נסתכל על מתודות שימושיות של מערכים או מתודות שימושיות הקשורות למערכים, המאפשרות לנו להפוך מחרוזת למערך ומערך למחרוזת ונלמד כיצד להכניס איברים נוספים לתוך מערכים או להסיר איברים ממערך. 

+ +

המרה בין מחרוזות ומערכים

+ +

הרבה פעמים אנחנו נקבל מידע גולמי אשר נמצא במחרוזת ארוכה ונרצה להפריד אותו לפריטי מידע אשר עמם נוכל לעשות שימוש באמצעות המרתה של המחרוזת למבנה אחר.

+ +

על מנת לעשות זאת, אנחנו נעשה שימוש במתודה {{jsxref("String.prototype.split()","split()")}}. מתודה זו ממירה מחרוזת למערך ומקבלת פרמטר אחד - התו שהמתודה תחפש בתוך המחרוזת שנרצה להמיר למערך וכאשר היא תמצא את אותו תו בכל פעם, היא תפריד בין החלק במחרוזת שנמצא לפני תו זה לבין החלק במחרוזת שנמצא אחריו, וכך היא בעצם מחלקת את המחרוזת לאיברים במערך. התוצאה של מתודה זו מערך שהאיברים שלו הם המחרוזות משנה שהופרדו.

+ +
+

לתשומת לב: מבחינה טכנית זוהי מתודה של מחרוזות ולא מתודה של מערכים.

+
+ +
    +
  1. בואו ננסה להבין כיצד מתודה הזו עובדת: צרו מחרוזת בקונסולה כגון זו: +
    let myData = 'Manchester,London,Liverpool,Birmingham,Leeds,Carlisle';
    +
  2. +
  3. עכשיו הפרידו בין התווים במחרוזת באמצעות המתודה {{jsxref("String.prototype.split()","split()")}} כך שכל פעם שיופיע התו , תבוצע העברה של התווים שלפניו לאיבר חדש במערך שנקרא myArray: +
    let myArray = myData.split(',');
    +myArray;
    +
  4. +
  5. נסו למצוא את האורך של המערך החדש וכן לקבל את הערך של חלק מהאיברים שלו: +
    myArray.length;
    +myArray[0]; // the first item in the array
    +myArray[1]; // the second item in the array
    +myArray[myArray.length-1]; // the last item in the array
    +
  6. +
  7. ניתן כמובן גם להמיר מערך למחרוזת באמצעות שימוש במתודה {{jsxref("Array.prototype.join()","join()")}}. נסו את הקוד הבא: +
    let myNewString = myArray.join(',');
    +myNewString;
    +
  8. +
  9. דרך נוספת של המרת מערך למחרוזת נוכל לעשות באמצעות שימוש במתודה {{jsxref("Array.prototype.toString()","toString()")}}.
  10. +
  11. המתודה ()toString הרבה יותר פשוטה מאשר ()join שכן היא לא מקבלת שום פרמטר/ארגומנט, אך יש לה מספר הגבלות. עם המתודה ()join אנחנו יכולים להגדיר איזה תו אנחנו נרצה שיפריד בין התווים במחרוזת. נסו לדוגמא להריץ שוב את שורה מספר 4, אך עם תו מפריד אחד כמו / או -. +
    let dogNames = ['Rocket','Flash','Bella','Slugger'];
    +dogNames.toString(); //Rocket,Flash,Bella,Slugger
    +
  12. +
+ +

הוספה והסרה של איברים במערך

+ +

בחלק זה נלמד כיצד להוסיף ולהסיר איברים במערך. אנו נעשה שימוש במערך myArray שהוגדר למעלה. לנוחיותכם, הנה הוא שוב:

+ +
let myArray = ['Manchester', 'London', 'Liverpool', 'Birmingham', 'Leeds', 'Carlisle'];
+ +

על מנת להוסיף איבר לסוף של מערך אנחנו משתמשים במתודות {{jsxref("Array.prototype.push()","push()")}} ובמתודה {{jsxref("Array.prototype.pop()","pop()")}} להסיר איבר מסוף המערך.

+ +
    +
  1. ננסה תחילה את המתודה ()push — שימו לב שאנחנו צריכים לכלול איבר אחד או יותר כארגומנט/פרמטר למתודה זו, אשר אותו נרצה להכניס לסוף המערך: + +
    myArray.push('Cardiff');
    +myArray;
    +myArray.push('Bradford', 'Brighton');
    +myArray;
    +
    +
  2. +
  3. כשאנו מבצעים את המתודה הזו, אנו מקבלים כערך מוחזר את ה-length החדש של המערך, לאחר ההוספה. אם נרצה לשמור את ה-length החדש, אנחנו נצטרך לשמור אותו במשתנה חדש: +
    let newLength = myArray.push('Bristol');
    +myArray;
    +newLength;
    +
  4. +
  5. הסרה של האיבר האחרון במערך מתבצע באמצעות המתודה ()pop על המערך. נסו את הקוד הבא: +
    myArray.pop();
    +
  6. +
  7. האיבר האחרון במערך הוסר, והערך המוחזר של המתודה זו היא האיבר האחרון שהוסר. על מנת לשמור את האיבר הזה במשתנה חדש, ניתן לרשום את הקוד הבא: +
    let removedItem = myArray.pop();
    +myArray;
    +removedItem;
    +
  8. +
+ +

{{jsxref("Array.prototype.unshift()","unshift()")}} וכן {{jsxref("Array.prototype.shift()","shift()")}} עובדות בדיוק אותו הדבר כמו ש-()push ו- ()pop, בהתאמה, למעט העבודה שהן מוסיפות/מסירות איברים מתחילת המערך ולא מסופו.

+ +
+

לתשומת לב:{{jsxref("Array.prototype.push()","push()")}} ו- {{jsxref("Array.prototype.pop()","pop()")}} המתודות משנות את מערך המקור.

+
+ +
    +
  1. מתודת ()unshift — הזינו את הקוד הבא לקונסולה: + +
    myArray.unshift('Edinburgh');
    +myArray;
    +
  2. +
  3. מתודת ()shift— הזינו את הקוד הבא לקונסולה: +
    let removedItem = myArray.shift();
    +myArray;
    +removedItem;
    +
  4. +
+ +

תרגול עצמאי : הדפסת המוצרים

+ +

נחזור לדוגמא שנתנו בתחילת המאמר - הדפסת שמות המוצרים והמחירים שלהם על חשבונית, וכן חישוב של המחירים שלהם בתחתית החשבונית. בדוגמא הבאה יש שורות עם הערות המכילות מספרים (לדוגמא: number 1). כל שורה שכזו נועדה לציין בפניכם את המיקום שבו תצטרכו להוסיף קוד לקוד הקיים:

+ +
    +
  1. מתחת להערה number 1 // יש מספר של מחרוזות, כאשר כל אחת כוללת שם של מוצר והמחיר שלו, מופרדים על ידי הסימן ;. אנו נרצה שתהפכו את המחרוזות הללו למערך ותאחסנו אותו במשתנה שנקרא products.
  2. +
  3. בשורה שבה נמצאת העקב number 2 // נמצאת לולאת ה-for שלנו. בשורה זו יש כרגע i <= 0, שזהו מבחן תנאי אשר גורם ל-for loop לרוץ רק פעם אחת, מכיוון שבפועל הוא ״תפסיק לרוץ כאשר i לא קטן יותר או שווה ל-0״, ו-i מתחיל ב-0. אנו נרצה שתחליפו את התנאי זה בקוד אחר כך שהלולאה תפסיק לרוץ כאשר i לא יהיה קטן יותר מהאורך של products.
  4. +
  5. מתחת להערה number 3 // אנו רוצים שתכתבו קוד שמפצל את האיבר הנוכחי במערך (name:price) ל-2 איברים נפרדים - אחד כולל את שם הפריט ואחד הכולל את מחירו. אם אתם לא בטוחים איך לבצע זאת, ראו מתודות שימושיות של מחרוזות והעמיקו בחלק {{anch("המרה בין מחרוזות ומערכים")}} של מאמר זה.
  6. +
  7. כחלק מהקוד למעלה, אולי גם נרצה להמיר את המחירים ממחרוזת למספר. אם אתם לא זוכרים כיצד לבצע זאת, קיראו את המאמר הבא, בחלק של ״מספרים מול מחרוזות״.
  8. +
  9. בראשית הקוד הנוכחי קיים משתנה שנקרא total אשר הוצהר והושם לו ערך של 0. בתוך הלולאה (מתחת number 4 //) אנו נרצה שתוסיפו שורת קוד שמוסיפה את האיבר שמייצג את המחיר הנוכחי למשתנה total בכל ריצה של הלולאה, כך שבסוף, המחיר הכולל (total)יודפס לחשבונית. אולי תרצו לחזור ולעיין ב-אופרטורים להשמה על מנת לעשות זאת.
  10. +
  11. בנוסף, נרצה שתשנו את השורה שמתחת להערה // number 5// כך שהמשתנה itemText יהיה בצורת כתיבה הזו לכל איבר ל-"current item name — $current item price", לדוגמא: "Shoes — $23.99" , כך שהמידע יוצג בתצורה הזו על גבי החשבונית. שימו לב שמדובר באיחוד של מחרוזות, לא משהו מורכב מדי שלא למדנו כבר.
  12. +
+ + + +

{{ EmbedLiveSample('Playable_code', '100%', 730, "", "", "hide-codepen-jsfiddle") }}

+ +

למידה עצמאית: 5 החיפושים האחרונים

+ +

שימוש נפוץ שאנחנו עושים במתודות של מערכים כמו {{jsxref("Array.prototype.push()","push()")}} ו- {{jsxref("Array.prototype.pop()","pop()")}} הוא כאשר אנחנו שומרים רישום של מספר פריטים מסויימים כגון עשרת החיפושים האחרונים שביצע המשתמש או כאשר אנחנו משתמשים באנימציה המציגה כמות מסויימת של פריטים המוצגים על גבי המסך המתחלפים ביניהם, כך שכל פעם יהיה רק מספר מסויים של פריטים. בדוגמאות אלו אובייקטים חדשים נוצרים ומתווספים למערך ואילו ישנים נמחקים על מנת לשמור על המספר שרצינו.

+ +

בדוגמאות הבאות אנחנו הולכים לעשות שימוש פשוט יחסית במתודות אלו - יש לנו אתר עם תיבת חיפוש. הרעיון הוא שכאשר ערכים מוכנסים לתיבת החיפוש, חמשת החיפושים הקודמים מוצגים ברשימה. כאשר כמות החיפושים הקודמים עולה על חמש, החיפוש הקודם ביותר נמחק מהרשימה ובמקומו נכנס החיפוש האחרון ביותר בתחילת הרשימה, כך שתמיד יוצגו לנו חמשת החיפושים האחרונים.

+ +
+

לתשומת לב: ביישום חיפוש אמיתי, יתאפשר לנו רוב הסיכויים ללחוץ על החיפושים הקודמים ולחזור לאותם חיפושים. בדוגמא הבא נרצה להשאיר את הנושא פשוט.

+
+ +

על מנת להשלים את המשימה, הנכם נדרשים:

+ +
    +
  1. להוסיף שורת מתחת להערה number 1// שמוסיפה את הערך הנוכחי שהוזן לתיבת החיפוש לתוך תחילת המערך. ניתן למצוא את הערך שהוזן לתיבת החיפוש באמצעות searchInput.value.
  2. +
  3. הוסיפו מתחת להערה number 2// שורת קוד שמסירה את הערך שנמצא כרגע בסוף המערך.
  4. +
+ + + +

{{ EmbedLiveSample('Playable_code_2', '100%', 700, "", "", "hide-codepen-jsfiddle") }}

+ +

לסיכום

+ +

לאחר קריאה של מאמר זה, אתם ככל הנראה מבינים כמה מערכים הם שימושים עבורנו. אנחנו נראה אותם לאורך כל הדרך, בדרך כלל בצירוף לולאת for על מנת לבצע פעולה כלשהו על כל איבר במערך. אנחנו נלמד במודול הבא את הדברים השימושיים והבסיסיים שניתן לבצע עם לולאות מסוגים שונים, וביניהן לולאות for.

+ +

כעת, בצעו את התרגול הנמצא במאמר הבא, המרכז את מרבית הנושאים שלמדנו במודול זה.

+ +

ראו גם

+ + + +

{{PreviousMenuNext("Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps/Silly_story_generator", "Learn/JavaScript/First_steps")}}

+ +

במודול זה

+ + diff --git a/files/he/learn/javascript/first_steps/index.html b/files/he/learn/javascript/first_steps/index.html new file mode 100644 index 0000000000..1cccf0cf39 --- /dev/null +++ b/files/he/learn/javascript/first_steps/index.html @@ -0,0 +1,64 @@ +--- +title: צעדים ראשונים ב - JavaScript +slug: Learn/JavaScript/First_steps +tags: + - JavaScript + - אופרטורים + - מאמר + - מדריך + - מודול + - מחרוזות + - מספרים + - מערכים + - משימה + - משתנים + - מתחילים +translation_of: Learn/JavaScript/First_steps +--- +
{{LearnSidebar}}
+ +

במודול JavaScript הראשון שלנו, אנחנו קודם כל נענה על כמה שאלות בסיסיות כמו "מהי JavaScript?", "איך היא ניראת?", ו"מה היא יכולה לעשות?", לפני שנתקדם לניסיון הפרקטי הראשון בכתיבת JavaScript. לאחר מכן נדון בכמה תכונות מפתח של JavaScript בפירוט, כגון משתנים, מחרוזות, מספרים ומערכים.

+ +

דרישות מוקדמות

+ +

לפני שנתחיל מודול זה, אינכם צריכים כל ידע מוקדם בJavaScript, אבל יש לכם צורך בהיכרות עם  HTML ו-CSS. מומלץ לעבור על המודולים הבאים לפני תחילת הלימוד אודות JavaScript:

+ + + +
+

הערה: אם אתם עובדים על מחשב\טבלט\מכשיר אחר שאין לכם אפשרות ליצור עליו קבצים אישיים, אתם יכולים לנסות את (רוב) דוגמאות הקוד על תוכנות קוד אינטרנטיות כמו JSBin או Thimble.

+
+ +

מדריכים

+ +
+
מה זה JavaScript?
+
ברוכים הבאים לקורס JavaScript למתחילים של MDN! במאמר ראשון זה אנו נסתכל על  JavaScript מלמעלה, ונענה על שאלות כמו "מה זה?", ו-"מה זה עושה?", ונדאג שתרגישו בנוח עם המטרה של JavaScript.
+
צלילה ראשונית לתוך JavaScript
+
לאחר שלמדתם משהו על התאוריה של JavaScript, ומה אתם יכולים לעשות איתה, נמשיך לקורס מזורז על הפיצ'רים הבסיסיים של JavaScript באמצעות הדרכה מעשית בלבד. כאן נבנה משחק "נחש את המספר" פשוט, צעד אחר צעד.
+
מה השתבש? פתרון בעיות ב-JavaScript
+
כשבניתם את משחק ״נחש את המספר״ במאמר הקודם, בטח שמתם לב שהוא לא עבד. אל חשש - המאמר הנוכחי נועד לחסוך לך זמן בפתרון הבעיה ולהעניק לך כמה טיפים פשוטים איך למצוא ולתקן שגיאות בתוכניות JavaScript.
+
אחסון האינפורמציה שאתם צריכים — משתנים
+
לאחר קריאת המאמרים הקודמים אתם אמורים לדעת מה היא JavaScript, מהם היכולות שלה, איך להשתמש בה לצד טכנולוגיות אינטרנט אחרות, ואיך ניראים הפיצ'רים הראשיים שלה במבט מלמעלה. במאמר זה נקבל את הבסיס האמיתי, בהתבוננות על איך לעבוד עם אבני הבנין הבסיסיות ביותר של JavaScript — המשתנים.
+
מתמתיקה בסיסית ב-JavaScript - מספרים ואופרטורים
+
בחלק הזה של הקורס, נדון במתמתיקה של JavaScript - כיצד אנו יכולים לצרף אופרטורים שונים ואפשרויות נוספות על מנת לבצע מניפולציות שונות על מספרים לצרכים שלנו.
+
התמודדות עם טקסט - מחרוזות ב-JavaScript.
+
במאמר זה נתמקד במחרוזות - כך טקסט נקרא בתכנות. נסכתל על הדברים הבסיסיים שצריך לדעת על מחרוזות כשלומדים תכנות בשפת JavaScript, כמו יצירת מחרוזות, חיבור מחרוזות וכיוצ״ב.
+
מתודות שימושיות של מחרוזות
+
לאחר שלמדנו את הבסיס של מחרוזות, נלמד מס׳ פעולות שימושיות שאנחנו יכולים לבצע על המחרוזות באמצעות מתודות מובנות, כגון מציאת האורך של מחרוזת טקס, חיבור ופיצול של מחרוזות, הוצאת תו אחד מתוך מחרוזת ועוד.
+
מערכים
+
במאמר האחרון של מודול זה, נסתכל על מערכים - דרך מסודרת לאחסכן רשימה של פריטי מידע, תחת משתנה אחד. נבין מדוע שימוש במערך הוא שימושי מאוד, ולאחר מכן נבין כיצד ליצור מערך, לאחזר מערך, להוסיף או להסיר איברים ממערך ועוד. 
+
+ +

בוחנים

+ +

הבחנים הבאים יבדקו את ההבנה שלכם בבסיס של JavaScript כפי שנלמד במדריך.

+ +
+
יישום אינטרנט ליצירת סיפורים טיפשיים
+
במשימה זו אתם תתבקשו לקחת את הידע שלמדתם במאמרים של המודול הזה, ולממש אותם בכך שתיצרו יישום שמייצר סיפורים טיפשיים באופן אקראי. בהצלחה!.
+
diff --git a/files/he/learn/javascript/first_steps/math/index.html b/files/he/learn/javascript/first_steps/math/index.html new file mode 100644 index 0000000000..e5c22c141f --- /dev/null +++ b/files/he/learn/javascript/first_steps/math/index.html @@ -0,0 +1,427 @@ +--- +title: מתמתיקה בסיסית ב-JavaScript - מספרים ואופרטורים +slug: Learn/JavaScript/First_steps/Math +translation_of: Learn/JavaScript/First_steps/Math +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps/Strings", "Learn/JavaScript/First_steps")}}
+ +

בשלב זה של הקורס, נדון קצת במתמתיקה שבשפת JavaScript - איך אנחנו יכולים להשתמש ב - {{Glossary("Operator","operators")}} ועוד אפשרויות על מנת להצליח לבצע מניפולציות וחישובים שונים על מספרים לצרכים שלנו

+ + + + + + + + + + + + +
ידע מוקדם:הבנה בסיסית של מחשב, הבנה בסיסית של  HTML, CSS ו - JavaScript.
מטרה:הכרות עם שימוש במתמתיקה באופן בסיסי ב-JavaScript.
+ +

כולנו אוהבים מתמטיקה

+ +

האמת לא ממש. חלקנו כן וחלקנו ממש לא. אך לא ניתן להכחיש את העובדה שמתמטיקה היא נדבך חשוב בחיים ובתכנות בפרט. הרבה ממה שאנחנו עושים מתבסס על עיבוד מידע מספרי, חישוב ערכים חדשים וכד׳ ולכן לא נופתע לדעת של-JavaScript יש סט מלא של פונקציות מתמתיטקיות מובנה בה.

+ +

מאמר זה ידון רק בחלקים הבסיסים שאנחנו צריכים לדעת כרגע.

+ +

סוגי מספרים

+ +

בתכנות, אפילו המספר העשרוני שאנחנו מכירים, הוא יותר מורכב ממה שנאחנו חושבים. אנחנו מתשמשים במושגים שונים על מנת לתאר סוגים שונים של מספרים עשרוניים. לדוגמא:

+ + + +

יש לנו אפילו כמה מערכות של מספרים! לדוגמא, מערכת מספרים דצימלית היא מבוססת על בסיס 10, כלומר, היא עושה שימוש בספרות 0-9 בכל עמודה. אבל יש עוד. לדוגמא:

+ + + +

לפני שאתם מתחילים לחשוש ולהתבלבל, תנשמו. נדיר שנשתמש במספרים שאינם מספרים דצימליים.

+ +

חדשות טובות נוספות הן שלא כמו בשפות תכנות אחרות, לשפת JavaScript יש רק סוג מידע אחד עבודה מספרים - {{jsxref("Number")}}. כלומר, לא משנה איזה סוג מספרים אנחנו נקבל/נזין בקוד, אנחנו נטפל בו בדיוק באותה צורה.

+ +

זה הכל מספרים

+ +

בוא נשחק קצת עם המספרים ונבין את הסינטקס הבסיסי שנצטרך. הכניסו את הקוד הבא לקונסולה:

+ +
    +
  1. קודם כל, נצהיר על שני משתנים ונשים בהם ערכים. לאחר מכן נזין את שמות המשתנים בקונסולה לוודא שהערכים הושמו כראוי: +
    let myInt = 5;
    +let myFloat = 6.667;
    +myInt;
    +myFloat;
    +
  2. +
  3. מספרים אלו בעצם ערכים שנרשמים ללא גרשיים - נסו להזין מספרים עטופים בגרשיים וראו מה קורה.
  4. +
  5. בוא נבדוק האם הערכים השונים שהזנו הם מאותו סוג. האופרטור שבודק את זה הוא {{jsxref("Operators/typeof", "typeof")}}. רשמו את הקוד הבא מתחת לקוד הנוכחי: +
    typeof myInt;
    +typeof myFloat;
    + אתם אמורים לקבל "number" בשני המקרים. ברור לנו שעיסוק בסוג מספר אחד הרבה יותר קל מאשר עם כמה סוגים.
  6. +
+ +

Arithmetic operators - אופרטורים מתמתטיים

+ +

אופרטורים מתמטיים הם האופרטורים הבסיסים שאנחנו משתמשים בהם על מנת לבצע חישובים:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
אופרטורשםמטרהדוגמא
+חיבורחיבור6 + 9
-חיסורחיסור20 - 15
*כפלכפל3 * 7
/חילוקחילוק10 / 5
%שארית +

השארית מחלוקת שני מספרים

+
+

8 % 3 (מחזיר 2, שכן 3 נכנס ב- 8 פעמיים, והשארית היא 2,).

+
**חזקהמכפיל את ה-base ב-מעריך , לדוגמא, המספר שיהיה נקוב ב- base עם המספר שיהיה נקוב ב- מעריך יגרום להכפלה של המספר שבבסיס כפול המספר שבמעריך. הוצג לראשונה ב- EcmaScript 2016.5 ** 5 (מחזיר 3125, שזה זהה ל- 5 * 5 * 5 * 5 * 5).
+ +
+

לתשומת לב: לפעמים ניתקל במספרים המעורבים בחישובים כ- {{Glossary("Operand", "operands")}}.

+
+ +
+

לתשומת לבד: לפעמים אנחנו נראה שמשתמשים במתודה הישנה {{jsxref("Math.pow()")}} אשר פועלת בדרך דומה. לדוגמא, בקוד Math.pow(7, 3), 7 הבסיס הוא 7 ו-3 הוא המעריך בחזקה, והתוצאה תהיה 343. Math.pow(7, 3) is שזה שווה ל- 7**3.

+
+ +

כנראה לא צריך ללמד אתכם מתמתיקה בסיסית, אבל אנו רוצים לוודא את ההבנה שלכם לגבי הסינטקס. נסו להכניס את הדוגמאות הבאות לקונסולה על מנת להכיר את הסינטקס.

+ +
    +
  1. הכניסו דומאות פשוטות כמו: +
    10 + 7
    +9 * 8
    +60 % 3
    +
  2. +
  3. אתם גם יכולים לנסות להצהיר על משתנים להשים להם מספרים כערכים, ונסו לעשות עליהם חישובים - המשתנים יתנהגו בדיוק כמו שיתנהגו הערכים שהם מחזיקים בהם. כך לדוגמא: +
    let num1 = 10;
    +let num2 = 50;
    +9 * num1;
    +num1 ** 3;
    +num2 / num1;
    +
  4. +
  5. נסו להזין קצת ביטויים יותר מורכבים, כמו: +
    5 + 10 * 3;
    +num2 % 9 * num1;
    +num2 + num1 / 8 + 2;
    +
  6. +
+ +

כפי ששמתם לב, חלק מהחישובים שביצענו מחזירים לנו תוצאה בהתאם לכללי הקדימות המתמטיים:

+ +

סדר עדיפות אופרטורים

+ +

אם נסתכל על הדוגמא למעלה, נניח ש- num2 הוא 50 ו- num1 הוא 10 :

+ +
num2 + num1 / 8 + 2;
+ +

בני אדם רגילים עלולים להניח ש- "50 ועוד 10 שווה 60", ואז "8 ועוד 2 שווה 10", ואז "60 חלקי 10 שווה 6".

+ +

אבל הדפדפן הולך לפי כללי החישוב המתמטים "10 חלקי 8 שווה 1.25", ואז "50 עוד 1.25 ועוד 2 שווה 53.25".

+ +

זהו מה שנקרא סדר עדיפות בין אופרטורים — חלק מהאופרטורים יבוצעו או יחולו לפני אופרטורים אחרים כשהדפדפן ינסה לחשב את התוצאה של החישוב. סדר עדיפות בין אופרטורים בשפה הוא בהתאם למה שלמנו בשיעורי מתמתיקה - כפל וחילוק תמיד ראשונים, ואז חיבור וחיסור, כאשר החישוב מתבצע מצד שמאל לימין.

+ +

אם נרצה לעקוף זאת, נצטרך לעשות שימוש בסוגריים רגילות סביב לחלקים שנרצה לבצע קודם. כך, על נת לקבל את התוצאה של 6, נצטרף לרשום את הקוד בצורה כזאת:

+ +
(num2 + num1) / (8 + 2);
+ +

נסו כדי לראות.

+ +
+

לתשומת לב: רשימה מלאה של האופטורים ב- JavaScript וסדר העדיפות שלהם ניתן למצוא בביטויים ואופרטורים.

+
+ +

אופרטים להעלאה/הורדה - Increment and decrement operators

+ +

לפעמים אנחנו רוצים להוסיף לערך או להוריד ממנו מספר אחד. ניתן לבצע זאת בקלות באמצעות שימוש באופרטור (++) לצורך העלאה ב-1 ובאופרטור (--) לצורך הורדה ב-1. השתמשנו באופרטור ++ במשחק שלנו  "Guess the number" ב-מבט ראשוני ל- JavaScript כאשר הוספנו אחד למשתנה guessCount על מנת לעקוב אחר מספר הניחושים שביצע המשתשמש.

+ +
guessCount++;
+ +
+

לתשומת לב: אופרטורים אלו נמצאים בדרך כלל בלולאות, עליהן נלמד בהמשך הקורס. לדוגמא, אם אנחנו רוצים לעבור על רשימה של מחירים, ולהוסיף מס על כל אחד מהם, אנחנו יכולים להשתמש בלולאה על מנת לעבור על כל ערך ברשימה, ולעשות את החישוב המתאים של הוספת מס. האופטרטור הוספה ישמש להעביר אותנו לערך הבא כשנצטרך. ראה לדוגמא כיצד זה מבוצע בדף האינטרנט וגם בקוד המקור. בדקו האם אתם מזהים את האופרטורים שמשמשים להוספה/הורדה בתוך הלולאה, נדון בהם בהמשך.

+
+ +

ננסה לשחק קצת בקונסולה. על מנת להתחיל, שימו לב שאתם לא יכול החיל אותם ישר על מספר כלשהו, למרות שזה נראה מוזר, אבל בפועל, כשאנחנו מעלים את הערך, אנחנו לא מבצעים חישוב כלשהו, אלא אנחנו משימים את החדש, לאחר החישוב, בתוך המשתנה. הפעולה הבאה תחזיר לדוגמא שגיאה:

+ +
3++;
+ +

כלומר, אנחנו יכולים רק להעלות משתנה קיים ב-1. נסו להזין את הקוד הבא:

+ +
let num1 = 4;
+num1++;
+ +

משהו מוזר נוסף. כשאנחנו עושים זאת, הערך 4 מוחזר לנו בקונסולה. זה מכיוון שהדפדפן מחזיר את הערך הנוכחי ורק אז מעלה את הערך של המשתנה. ניתן לראות שהערך של המשתנה הועלה ב-1 אם נזין שוב את השם של המשתנה בקונסולה.

+ +
num1;
+ +

אותו הדבר לגבי --  נסו את הקוד הבא:

+ +
let num2 = 6;
+num2--;
+num2;
+ +
+

לתשומת לב: אנו יכולים לגרום לדפדפן לבצע זאת בצורה אחרת - כלומר, להעלות את המשתנה ב-1 ורק אז להחזיר לנו את הערך החדש של המשתנה באמצעות הוספת האופרטור לפני המשתנה ולא בסופו. נסו להזין את הקוד הבא ++num1 ואז --num2.

+
+ +

Assignment operators - אופרטורים להשמה

+ +

אופרטורים להשמה אלו אופרטים שמשימים ערך לתוך משתנה. ראינו זאת עם הבסיסי שבה: =- הוא פשוט משים את הערך מצד שמאל, למשתנה שמצויין מצד ימין.

+ +
let x = 3; // x contains the value 3
+let y = 4; // y contains the value 4
+x = y; // x now contains the same value y contains, 4
+ +

אך יש כאלה מורכבים יותר, שיכולים לתת לנו קיצורי דרך על מנת לרשום את הקוד שלנו נקי ויעיל יותר. הנפוצים הם:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
אופרטורשםמטרהדגומאקיצור עבור
+=חיבור והשמהמוסיף את הערך מצד ימין לערך שבמשתנה מצד שמאל, ואז מחזיר את הערך של המשתנה החדשx = 3;
+ x += 4;
x = 3;
+ x = x + 4;
-=חיסור והשמהמחסיר את הערך מצד ימין מתוך הערך שנמצא בתוך המשתנה מצד שמאל, ואז מחזיר את הערך של המשתנה החדשx = 6;
+ x -= 3;
x = 6;
+ x = x - 3;
*=כפל והשמהמכפיל את הערך מצד ימין עם הערך שנמצא במשתנה מצד שמאל, ואז מחזיר את הערך של המשתנה החדשx = 2;
+ x *= 3;
x = 2;
+ x = x * 3;
/=חילוק והשמהמחלק את הערך מצד ימין בערך שנמצא במשתנה מצד שמאל, ואז מחזיר את הערך של המשתנה החדשx = 10;
+ x /= 5;
x = 10;
+ x = x / 5;
+ +

נסו להזין חלק מהדוגמאות הרשומות למעלה לתוך הקונסולה, על מנת להבין את הרעיון. בכל מקרה, נסו לראות אם אתם מצליחים לדעת מה הערך שיוחזר לפני החישוב וההשמה.

+ +

כמובן שגם ניתן לבצע את החישובים וההשמות גם כאשר נמצאים משתנים משני צידי הסימן. לדוגמא:

+ +
let x = 3; // x contains the value 3
+let y = 4; // y contains the value 4
+x *= y; // x now contains the value 12
+ +
+

לתשומת לב: יש הרבה אופרטורים להשמה נוספים, אבל אלו הבסיסיים שאתם צריכים לדעת לעת עתה.

+
+ +

למידה אקטיבית: שינוי גודל של canvas box

+ +

בתרגיל זה נלמד כיצד לבצע מניפולציות על מספרים ואופרטורים, על מנת לשנות גודל של קופסא. הקופסא מצויירת באמצעות browser API אשר נקרא {{domxref("Canvas API", "", "", "true")}}. אין מה לדאוג לגבי איך הוא עובד, רק התרכזו בחישובים עצמם. הגובה והרוחב של הקופסא בפיקסלים יוגדרו על ידי המשתנים x ו- y, אשר קיבלו ערך התחלתי של 50.

+ +

{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/maths/editable_canvas.html", '100%', 620)}}

+ +

Open in new window

+ +

בבריבוע למעלה יש שתי שורות שמסומנות עם הערה - אלו השורות שאתם צריכים לעדכן על מנת להגדיל/להקטין את הקופסא, באמצעות שימוש באופרטורים השונים ו/או ערכים שונים. נסו את הדברים הבאים:

+ + + +

אל תדאגו אם אתם הורסים את הקוד לחלוטין. פשוט לחצו על הכפתור לאתחל את הכל.

+ +

Comparison operators - אופרטורים להשוואה

+ +

לפעמים נרצה לבצע מבחני אמת/שקר, ואז להריץ פעולות מסוימות בהתאם לתוצאת המבחן - בשביל זה נועדו אופרטורים להשוואה.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
אופרטורשםמטרהדוגמא
===השוואה מוחלטתאופרטור זה בודק הא הערכים מצד ימין וצד שמאל זהים לחלוטין5 === 2 + 4
!==שונים לחלוטיןבודק האם הערך מצד ימיןלא זהה לערך מצד שמאל5 !== 2 + 3
<קטן מ-בודק האם הערך בצד שמאל קטן מהערך בצד ימין.10 < 6
>גדול מ-בודק האם הערך בצד שמאל גדול מהערך בצד ימין.10 > 20
<=קטן מ- או שווה ל-בודק האם הערך בצד שמאל קטן מהערך בצד ימין או שווה לו.3 <= 2
>=גדול מ- או שווה ל-בודק האם הערך בצד שמאל גדול מהערך בצד ימין או שווה לו.5 >= 4
+ +
+

לתשומת לב: לפעמים תראו אנשים שמשתמשים באופרטור == או != במבחני בדיקת זהות/שונות שלהם. אלו אופרטורים תקינים לחלוטין בשפה, אבל הם שונים מ - ===/!==. הראשונים מבצעים בדיקה האם הערכים בצד ימין ובצד שמאל זהים מבחינת הערך עצמו, אך ״אדישים״ לגבי הזהות מבחינת סוג הערך. ואילו האחרונים מבצעים בדיקה של זהות/שונות מוחלטת - גם ערכים וגם סוג הערך. שימוש בבדיקת זהות/שונות מוחלטת נוטה להציג פחות שגיאות, אז המלצתנו היא להשתמש בהם.

+
+ +

אם תנסו להכניס כמה מהערכים הללו לקונסולה את תראה בחזרה ערכי true/false - אלו ערכים בולאינים, כפי שהזכרנו במאמר קודם. ערכים אלו מאוד שימושיים מכיוון שהם מאפשרים לבצע החלטות בקוד שלנו, ואנחנו משתמשים בהם בכל פעם שאנרצה לקבל החלטה מסוג כלשהו. בוליאנים יכולים לשמש עבור:

+ + + +

אנו נסתכל על דרך לכתוב קוד באמצעות שימוש בלוגיקה כשנלמד על משפטי תנאי במאמרים הבאים. לבינתיים, ראו דוגמא:

+ +
<button>Start machine</button>
+<p>The machine is stopped.</p>
+
+ +
const btn = document.querySelector('button');
+const txt = document.querySelector('p');
+
+btn.addEventListener('click', updateBtn);
+
+function updateBtn() {
+  if (btn.textContent === 'Start machine') {
+    btn.textContent = 'Stop machine';
+    txt.textContent = 'The machine has started!';
+  } else {
+    btn.textContent = 'Start machine';
+    txt.textContent = 'The machine is stopped.';
+  }
+}
+ +

{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/maths/conditional.html", '100%', 100)}}

+ +

פתח בחלון חדש

+ +

אתם יכולים לראות את האופרטור להשוואה מתקיים בתוך פונקציית ()updateBtn . במקרה זה, אנחנו לא בודקים האם שני ביטויים מתמידים הם בעלי ערך זהה, אלא אנחנו בודקים האם תוכן הטקסט של הכפתור כולל בתוכו מחרוזת מסויימת - אבל עדיין מדובר באותו עקרון שלמדנו עליו. אם הכפתור כולל בתוכו מחרוזת "Start machine" כשלוחצים עליו, אזי נשנה את השם שלו בהתאם. אם הוא כולל מחרוזת "Stop machine" אזי נבצע החלפה שוב.

+ +
+

לתשומת לב: אפשרות כזו להחליף בין שני מצבים נקראת toggle. הוא מחליף פשוט בין מצב אחד למצב שני.

+
+ +

לסיכום

+ +

במאמר זה כיסינו את הידע החשוב והכרחי שאתם צריכים לדעת על מספרים בשפה. לבינתיים. אתם תראו מספרים דיי הרבה פעמים, לכל אורך הלימוד, אז זה רעיון טוב שתתחילו להתרגל אליהם ולהבין אותם. אל תפחדו מהם.

+ +

במאמר הבא נבין איך השפה מאפשרת לנו לבצע מניפולציות שונות על מחרוזות וטקסטים ויצד נוכל לבצע בהם שימוש.

+ +
+

לתשומת לב: אם אתם מעוניינים להרחיב את הידיעות בנושא, ראו את הדפים שלנו בנושא  Numbers and dates ו-Expressions and operators.

+
+ +

{{PreviousMenuNext("Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps/Strings", "Learn/JavaScript/First_steps")}}

+ +

במודול זה

+ + diff --git a/files/he/learn/javascript/first_steps/silly_story_generator/index.html b/files/he/learn/javascript/first_steps/silly_story_generator/index.html new file mode 100644 index 0000000000..8c4ca6772a --- /dev/null +++ b/files/he/learn/javascript/first_steps/silly_story_generator/index.html @@ -0,0 +1,139 @@ +--- +title: Silly story generator +slug: Learn/JavaScript/First_steps/Silly_story_generator +translation_of: Learn/JavaScript/First_steps/Silly_story_generator +--- +
{{LearnSidebar}}
+ +
{{PreviousMenu("Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}
+ +

בתרגול זה, תתבקשו ליישם את מה שלמדתם בכל המאמרים האחרונים במודול הנוכחי על מנת ליצור יישום קטן שמייצר סיפורים טיפשיים באופן רנדומלי. 

+ + + + + + + + + + + + +
ידע מוקדם:אנא וודאו כי עברתם על כל המאמרים במודול זה בטרם ביצוע התרגול.
מטרה:לוודא הבנה של יסודות שפת JavaScript ושימוש במשתנים, מספרים,אופרטורים, מחרוזות ומערכים. 
+ +

נקודת התחלה

+ +

על מנת להתחיל:

+ + + +
+

לתשומת לב: לחילופין, אתם יכולים לעשות שימוש ב- JSBin או Thimble על מנת להשלים את התרול. אתם יכולים להדביק לתוכם את ה HTML, CSS ואת JavaScript.

+
+ +

תקציר הפרוייקט

+ +

קיבלתם לידיכם HTML/CSS גולמי ומס׳ מחרווזת טקסט וכן מס׳ פונקציות של JavaScript. הנכם נדרשים לכתוב את הקוד הרלוונטי על מנת להפוך אותם לתוכנית שעושה את הדברים הבאים:

+ + + +

צילום המסך הבא יסייע לכם להבין כיצד זה אמור להיראות:

+ +

+ +

לתת לכם קצת יותר הכוונה, הסתכלו בפתרון העובד (אך אל תסתכלו על קוד המקור, אלא אם ממש נתקעתם)

+ +

פעולות נדרשות

+ +

אלו הפעולות שתידשו לבצע על מנת להשלים את התרגול בהצלחה

+ +

התקנה בסיסית:

+ +
    +
  1. צרו קובץ חדש שנקרא בשם main.js, באותה תיקיה שבה נמצא קובץ index.html שלכם
  2. +
  3. החילו את קובץ ה-JavaScript לתוך קובץ ה-HTML כפי שלמדנו באמצעות {{htmlelement("script")}} עם קישור ל-main.js. שימו אותו לפני תגית הסיום של </body>.
  4. +
+ +

אתחול משתנים ופונקציות:

+ +
    +
  1. בקובץ הטקסט הגולמי העתיקו את כל הקוד שמופיע תחת הכותרת "1. COMPLETE VARIABLE AND FUNCTION DEFINITIONS" והדביקו אותו בחלקו העליון של הקובץ main.js.זה נותן שלשה משתנים שמכילים הפניות לשדה הטקסט "Enter custom name" (המשתנה: customName) ולכפתור "Generate random story" (המשתנה:randomize) ולאלמנט {{htmlelement("p")}} (המשתנה:story) שבתחתית חלק ה HTML שאליו יועתק הסיפור בהתאמה. בנוסף יש לך פונקציה שנקראת randomValueFromArray() שלוקחת מערך, ומחזירה אחד מהפריטים המאוחסנים בתוך המערך באופן אקראי
  2. +
  3. כעת התבוננו בקטע השני שבקובץ הטקסט הגולמי "2. RAW TEXT STRINGS" זה מכיל מחרוזות טקסט   that will act as input into our program. We'd like you to contain these inside variables inside main.js: +
      +
    1. Store the third set of three strings inside an array called insertZ.
    2. +
    3. Store the second set of three strings inside an array called insertY.
    4. +
    5. Store the first set of three strings inside an array called insertX.
    6. +
    7. Store the first, big long, string of text inside a variable called storyText.
    8. +
    +
  4. +
+ +

Placing the event handler and incomplete function:

+ +
    +
  1. Now return to the raw text file.
  2. +
  3. Copy the code found underneath the heading "3. EVENT LISTENER AND PARTIAL FUNCTION DEFINITION" and paste it into the bottom of your main.js file. This: +
      +
    • Adds a click event listener to the randomize variable so that when the button it represents is clicked, the result() function is run.
    • +
    • Adds a partially-completed result() function definiton to your code. For the remainder of the assessment, you'll be filling in lines inside this function to complete it and make it work properly.
    • +
    +
  4. +
+ +

Completing the result() function:

+ +
    +
  1. Create a new variable called newStory, and set it's value to equal storyText. This is needed so we can create a new random story each time the button is pressed and the function is run. If we made changes directly to storyText, we'd only be able to generate a new story once.
  2. +
  3. Create three new variables called xItem, yItem, and zItem, and make them equal to the result of calling randomValueFromArray() on your three arrays (the result in each case will be a random item out of each array it is called on). For example you can call the function and get it to return one random string out of insertX by writing randomValueFromArray(insertX).
  4. +
  5. Next we want to replace the three placeholders in the newStory string — :insertx:, :inserty:, and :insertz: — with the strings stored in xItem, yItem, and zItem. There is a particular string method that will help you here — in each case, make the call to the method equal to newStory, so each time it is called, newStory is made equal to itself, but with substitutions made. So each time the button is pressed, these placeholders are each replaced with a random silly string. As a further hint, the method in question only replaces the first instance of the substring it finds, so you might need to make one of the calls twice.
  6. +
  7. Inside the first if block, add another string replacement method call to replace the name 'Bob' found in the newStory string with the name variable. In this block we are saying "If a value has been entered into the customName text input, replace Bob in the story with that custom name."
  8. +
  9. Inside the second if block, we are checking to see if the uk radio button has been selected. If so, we want to convert the weight and temperature values in the story from pounds and Fahrenheit into stones and centigrade. What you need to do is as follows: +
      +
    1. Look up the formulae for converting pounds to stone, and Fahrenheit to centigrade.
    2. +
    3. Inside the line that defines the weight variable, replace 300 with a calculation that converts 300 pounds into stones. Concatenate ' stone' onto the end of the result of the overall Math.round() call.
    4. +
    5. Inside the line that defines the temperature variable, replace 94 with a calculation that converts 94 Fahrenheit into centigrade. Concatenate ' centigrade' onto the end of the result of the overall Math.round() call.
    6. +
    7. Just under the two variable definitions, add two more string replacement lines that replace '94 fahrenheit' with the contents of the temperature variable, and '300 pounds' with the contents of the weight variable.
    8. +
    +
  10. +
  11. Finally, in the second-to-last line of the function, make the textContent property of the story variable (which references the paragraph) equal to newStory.
  12. +
+ +

רמזים וטיפים

+ + + +

Assessment

+ +

If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the discussion thread for this exercise, or in the #mdn IRC channel on Mozilla IRC. Try the exercise first — there is nothing to be gained by cheating!

+ +

{{PreviousMenu("Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}

+ +

In this module

+ + diff --git a/files/he/learn/javascript/first_steps/strings/index.html b/files/he/learn/javascript/first_steps/strings/index.html new file mode 100644 index 0000000000..8523f144ac --- /dev/null +++ b/files/he/learn/javascript/first_steps/strings/index.html @@ -0,0 +1,172 @@ +--- +title: "התמודדות עם טקסט\_— מחרוזות (Strings) ב-JavaScript" +slug: Learn/JavaScript/First_steps/Strings +translation_of: Learn/JavaScript/First_steps/Strings +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps")}}
+ +

כעת, אנו נשים את הפוקוס על מחרוזות - כך נקראים חלקים של טקסט בתכנות. במאמר זה אנחנו נסתכל על הדברים המשותפים שאנחנו חייבים לדעת על מחרוזות כשלומדים JavaScript, כמו יצירת מחרוזות, חיבור מחרוזות וכד׳.

+ + + + + + + + + + + + +
ידע מוקדם:הבנה בסיסית של מחשב, הבנה בסיסית של  HTML, CSS ו - JavaScript.
מטרה:הכרות עם הבסיס של מחרוזות וטקסט ב-JavaScript.
+ +

כוחן של מילים

+ +

מילים הן אחד הדברים החשובים לבני אדם - זוהי הדרך שמרבית מאיתנו מתקשרים אחד עם השני. מאחר ורשת האינטרנט היא בעיקרה מדיה המבוססת על טקסט המאפשרת לבני אדם להחליף ביניהם מידע, זה מאוד שימוש עבורנו לקבל שליטה על הדרך שבה מילים מוצגות ברשת האינטרנט. {{glossary("HTML")}} מעניק לנו את המבנה ואת המשמעות מאחורי הטקסט שלנו, {{glossary("CSS")}} מאפשר לנו לעצב אותו ואילו JavaScript מכילה מספר אפשרויות וכללים לבצע מניפולציות שונות על מחרוזות, ליצור הודעות/התראות שונות, להראות את הטקסט הנכון כשצריך ועוד.

+ +

כמעט כל התוכניות שעברנו עליהם בקורס עד כה כללו מניפולציה כלשהי על מחרוזות.

+ +

Strings — מחרוזות - הבסיס

+ +

אנו נעבוד עם מחרוזות בדיוק כמו שעבדנו עם מספרים, אך עם מספר הבדלים: נתחיל בכך שנפתח את הקונסולה ונזין מספר שורות קוד:

+ +

יצירת מחרוזת

+ +
    +
  1. על מנת להתחיל, הזן את השורות הבאות בקונסולה: +
    let string = 'The revolution will not be televised.';
    +string;
    + בדיוק כמו שעשינו עם מספרים, אנחנו מכריזים פה על משתנה ומשימים לו ערך של מחרוזת ואז מקבלים את הערך של המשתנה. ההבדל היחיד הוא שכאשר אנחנו כותבים מחרוזת, אנחנו צריכים להשתמש במרכאות כפולות "" או במרכאות בודדות - גרש מכל צד - ''.
  2. +
  3. אם לא נעשה זאת, או שנחסיר אותן בצד ימין או שמאל, אנחנו נקבל שגיאה. נסו להזין את השורות הבאות: +
    let badString = This is a test;
    +let badString = 'This is a test;
    +let badString = This is a test';
    + שורות קוד אלו לא יעבדו מכיוון שכל טקסט שאינו מוקף במלואו במרכאות נחשב כשם של משתנה או שם של מאפיין או מילה שמורה וכד׳. אם הדפדפן לא מוצא את אותה מילה, הוא מחזיר שגיאה. לדוגמא: "missing; before statement". אם הדפדפן יכול לראות מתי מתחילה מחרוזת, אבל לא מתי היא מסתיימת, מכיוון שחסר מרכאות בצד כלשהו, הוא יחזיר שגיאה כגון: "unterminated string literal". אם התוכנית שלנו מעלה שגיאות כאלו, צריך לחזור ולבדוק את כל המחרוזות ולוודא שלא שכחנו מרכאות.
  4. +
  5. הקוד הבא יעבוד אם הגדרנו לפני את המשתנה string: +
    let badString = string;
    +badString;
    + badString כעת הוגדר לקבל את אותו ערך כמו של string.
  6. +
+ +

מרכאות כפולות או בודדות

+ +
    +
  1. ב-JavaScript, אנחנו יכולים לבחור האם להשתמש במרכאות כפולות או במרכאות בודדות לשם עטיפת המחרוזת שלנו. שניהם יעבדו מצויין ובדיוק אותו דבר: +
    let sgl = 'Single quotes.';
    +let dbl = "Double quotes";
    +sgl;
    +dbl;
    +
  2. +
  3. יש מעט מאוד הבדלים ביניהם, וזה תלוי בכם במה להתשמש. אתם צריכים לבחור סוג אחד ואיתו להמשיך. צריך לזכור שלא ניתן להשתמש בשניהם במקביל כך שמצד אחד של מחרוזת יהיו מרכאות כפולות ומצד שני יהיו מרכאות בודדות, שכן זה יחזיר לנו שגיאה: +
    let badQuotes = 'What on earth?";
    +
  4. +
  5. הדפדפן יחשוב שהמחרוזת לא נסגרה מכיוון שכשאנחנו משתמשים בסוג אחד של מרכאות על מנת לעטוף טקסט, אנחנו יכולים להשתמש בסוג השני של המרכאות בתוך הטקסט עצמו. לדוגמא, השורות הקוד הבאות הן תקינות לחלוטין: +
    let sglDbl = 'Would you eat a "fish supper"?';
    +let dblSgl = "I'm feeling blue.";
    +sglDbl;
    +dblSgl;
    +
  6. +
  7. יחד עם זאת, צריך לזכור שאנחנו לא יכולים לכלול בתוך הטקסט את סוג המרכאות שאיתו אנחנו משתמשים על מנת לעטוף את אותו הטקסט. הדוגמא הבאה תציג לנו שגיאה, שכן הדפדפן לא יודע מתי המחרוזת מסתיימת: +
    let bigmouth = 'I've got no right to take my place...';
    + וזה מה שמוביל אותנו לנושא הבא. תווים לבריחה ממחרוזות.
  8. +
+ +

תווים לבריחה ממחרוזת

+ +

על מנת לתקן את הבעיה בקוד הקודם, אנחנו צריכים לברוח מסימן המרכאות אשר עוטף את הטקסט. תווי בריחה שכאלו משמעותם שאנחנו עושים משהו על מנת לוודא שהם ייקראו כטקסט רגיל ולא כחלק מהקוד שלנו. ב-JavaScript, אנחנו עושים את זה באמצעות שימוש בסימן \נסו את זה:

+ +
let bigmouth = 'I\'ve got no right to take my place...';
+bigmouth;
+ +

זה עובד מצוין. אנחנו יכולים גם לברוח מתווים אחרים באותה צורה. לדוגמא: "\,  ויש עוד. ראו Escape notation לפרטים נוספים.

+ +

Concatenating strings - שרשור מחרוזות

+ +
    +
  1. שרשור נשמעת כמו מילה מורכבת שמשמעותה הפשוטה הוא חיבור ביחד. חיבור מחרוזות יחד ב-JavaScript מתבצע באמצעות האופרטור (+), באותה צורה כשהשתמשנו בו לביצוע חיבור בין מספרים, אבל בהקשר שלנו הוא מבצע משהו אחר. נסו את הקוד הבא בקונסולה: +
    let one = 'Hello, ';
    +let two = 'how are you?';
    +let joined = one + two;
    +joined;
    + התוצאה של המשתנה שנקרא joined תכיל את הערך של "Hello, how are you?"
  2. +
  3. במשתנה השלישי, פשוט חיברנו שתי מחרוזות יחד, אך אנחנו יכולים לחבר כמה מחרוזות שנרצה, כל עוד אנחנו כוללים את סימן + בין כל אחת מהמחרוזות. נסו לדוגמא: +
    let multiple = one + one + one + one + two;
    +multiple;
    +
  4. +
  5. אתם גם יכולים לערבב בין משתנים לבין מחרוזות בפועל. נסו את הבא: +
    let response = one + 'I am fine — ' + two;
    +response;
    +
  6. +
+ +
+

לתשומת לב: כשאנחנו מכניסים מחרוזת טקסט ממשית לתוך הקוד שלנו, כשהיא עטופה במרכאות (כפולות או בודדות), זה נקרא string literal.

+
+ +

Concatenation in context - שרשור בתוכן

+ +

בוא נסתכל על שרשור בפועל - הנה דוגמא ממאמרים קודמים בקורס:

+ +
<button>Press me</button>
+ +
const button = document.querySelector('button');
+
+button.onclick = function() {
+  let name = prompt('What is your name?');
+  alert('Hello ' + name + ', nice to see you!');
+}
+ +

{{ EmbedLiveSample('Concatenation_in_context', '100%', 50, "", "", "hide-codepen-jsfiddle") }}

+ +

כאן אנחנו משתמשים ב- {{domxref("window.prompt()", "window.prompt()")}} פונקציה בשורה 4, אשר מבקשת מהמשתמש לענות לשאלה באמצעות חלון קופץ, ולאחר מכן מאחסנת את הטקסט שהמשתמש הכניס לתוך משתנה נתון - במקרה הזה - המשתנה name.

+ +

לאחר מכן אנחנו משתמשים ב-{{domxref("window.alert()", "window.alert()")}} בשורה 5, על מנת להציג למשתמש חלון קופץ נוסף המיכל מחרוזת שהרכבנו משתי מחרוזות בנויות ומהמשתנה name, באמצעות שרשור של המחרוזות.

+ +

מספרים vs. מחרוזות

+ +
    +
  1. מה יקרה כאשר אנחנו ננסה לחבר (לשרשר) בין מחרוזת לבין מספר? נזין את הקוד הבא בקונסולה: +
    'Front ' + 242;
    +
    + היינו מצפים שניסיון כזה יחזיר לנו שגיאה, אך זה עובד בצורה מצויינת. נסיון להציג מחרוזת כמספר לא עושה הגיון, אבל הצגת מספר כמחרוזת כן, ולכן הדפדפן ממיר את המספר למחרוזת ומאחד בין שתי המחרוזות.
  2. +
  3. ניתן אפילו לעשות זאת עם שני מספרים - אנחנו יכולים להכריח מספר להפוך למחרוזת על ידי עטיפה שלו במרכאות. נסו את הקוד הבא. שימו לב שאנחנו משתמשים באופרטור typeof על מנת לבדוק האם הערך של המשתנה הוא מספר או מחרוזת: +
    let myDate = '19' + '67';
    +typeof myDate;
    +
  4. +
  5. אם יש לנו משתנה שיש לו ערך של מספר ואנחנו רוצים להמירו למחרוזת ללא ביצוע שינוי נוסף בו, או יש לנו משתנה שיש לו ערך שהוא מחרוזת ואנחנו רוצים להמירו למספר ולא לעשות בו שינוי נוסף, אנחנו יכולים להשתמש במתודות הבאות: +
      +
    • האובייקט {{jsxref("Number")}} יהפוך כל דבר שמועבר אליו למספר, אם הוא יכול. נסו את הקוד הבא: +
      let myString = '123';
      +let myNum = Number(myString);
      +typeof myNum;
      +
    • +
    • מצד שני, לכל מספר יש מתודה שנקראת ()toString שתמיר כל מספר למחרוזת תואמת. נסו לדוגמא את הקוד הבא: +
      let myNum = 123;
      +let myString = myNum.toString();
      +typeof myString;
      +
    • +
    + אלו יכולים להיות מאוד שימושיים בסיטואציות שונות. לדומא, אם משתמש מכניס מספר לתוך שדה טקסט בטופס, זה תמיד יהיה מחרוזת, גם אם הוא הזין מספרים. לעומת זאת, אם אנחנו רוצים להוסיף את המספר שהמשתמש הזין למשהו, זה חייב להיות מספר, ולכן אנחנו נצטרך להעביר את הקלט הזה דרך ()Number. עשינו זאת בדיוק, בדוגמא שלנו ב-משחק ״נחש את הזיכרון״, בשורה 54.
  6. +
+ +

לסיכום

+ +

זה היה הבסיס של מחרוזת ב-JavaScript. במאמר הבא אנחנו נסתכל על מתודות מובנות הזמינות למחרוזות בשפה זו ונלמד כיצד אנחנו יכולים להשתמש בהם על מנת לבצע מניפולציות למחרוזות שלנו או לשנות את המבנה שלהן.

+ +

{{PreviousMenuNext("Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps")}}

+ +

במודול זה

+ + diff --git a/files/he/learn/javascript/first_steps/useful_string_methods/index.html b/files/he/learn/javascript/first_steps/useful_string_methods/index.html new file mode 100644 index 0000000000..8315262c35 --- /dev/null +++ b/files/he/learn/javascript/first_steps/useful_string_methods/index.html @@ -0,0 +1,673 @@ +--- +title: מתודות שימושיות של מחרוזות +slug: Learn/JavaScript/First_steps/Useful_string_methods +tags: + - JavaScript + - אובייקט + - חילוץ וחיבור מחרוזות + - מחרוזות + - מחרוזות ב-JavaScript + - מציאת האורך של מחרוזת + - מציאת חלק ממחרוזת +translation_of: Learn/JavaScript/First_steps/Useful_string_methods +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/First_steps/Strings", "Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}
+ +

לאחר שלמדנו את הבסיס של מחרוזות, נתקדם הלאה ונלמד אילו פעולות אנחנו יכולים לבצע על מחרוזות תוך שימוש במתודות מובנות, כגון מציאת אורך המחרוזת, חיבור ופיצול של מחרוזות, הפרדת תו בודד במחרוזת ועוד.

+ + + + + + + + + + + + +
ידע מוקדם:הבנה בסיסית של מחשב, הבנה בסיסית של  HTML, CSS ו - JavaScript.
מטרה: +

הבנה כי מחרוזות הן בעצם סוג של אובייקט, ולמידה כיצד להשתמש במתודות בסיסיות הזמינות עבור אובייקט מסוג שכזה וכיצד לבצע מניפלוציות במחרוזות.

+
+ +

מחרוזות הן בעצם סוג של אובייקט

+ +

רוב הדברים ב-JavaScript הן בעצם אובייקט. כאשר אנחנו יוצרים מחרוזת כזו לדוגמא:

+ +
let string = 'This is my string';
+ +

המשתנה שלנו בעצם הופך למעין מופע של אובייקט מחרוזת (a string object instance), וכתוצאה מכך לא מעט מתודות ומאפיינים הופכים לזמינים עבור המשתנה. 

+ +

ניתן לראות את רשימת המתודות ומאפיינים אלו בדף בנושא  {{jsxref("String")}} - ראו את הכמות הלא מבוטלת הזו של מתודות ומאפיינים. 

+ +

לפני שאתם נלחצים - אנחנו לא באמת צריכים לזכור את כל המתודות והמאפיינים הללו, לפחות לא בתחילת דרכנו. אך יש כאלו שנרצה לזכור ולתרגל שכן אנחנו נשתמש בהן לעיתים תכופות. 

+ +

נתחיל בתרגול על ידי הכנסת הדוגמאות הבאות לקונסולה:

+ +

מציאת האורך של מחרוזת

+ +

זהו מאפיין המאפשר לנו למצוא את האורך של המחרוזת - אנחנו פשוט משתמשים במאפיין {{jsxref("String.prototype.length", "length")}}. נסו להכניס את הקוד הבא בקונסולה:

+ +
let browserType = 'mozilla';
+browserType.length;
+ +

זה אמור להחזיר לכם את המספר 7, מכיוון שהמחרוזת ״mozilla״ מורכבת מ-7 תווים. זה מאוד שימושי מסיבות רבות: לדוגמא, לפעמים נרצה למצוא את האורך של כל שם ברשימה של שמות ואז להציג אותם לפי האורך שלהם, או לתת למשתמש הודעה ששם המשתמש שהוא הכניס הוא ארוך מדי אם הוא עבר אורך מסויים.

+ +

אחזור של תו ספציפי במחרוזת

+ +

בהקשר זה, אנחנו יכולים לקבל תו ספציפי במחרוזת, על ידי שימוש ב - סוגריים מרובעות בסוף המחרוזת שלנו - כלומר, אנחנו צריכים לכלול ([]) בסוף שם המשתנה שלנו.

+ +

בתוך הסוגריים המרובעות אנחנו צריכים להכניס את מס׳ התו שאנחנו רוצים לקבל בחזרה, כך שאם נרצה את התו הראשון במחרוזת, נזין את הקוד הבא:

+ +
browserType[0];
+ +

שימו לב שמחשבים מתחילים לספור מ-0 ולא מ-1. על מנת לקבל את התו האחרון של כל מחרוזת, אנחנו יכולים להשתמש בקוד הבא המבצע שימוש גם במאפיין length שלמדנו למעלה.

+ +
browserType[browserType.length-1];
+ +

האורך של "mozilla" הוא 7 תווים, אך מכיוון שהמונה (או יותר נכון - אינדקס) מתחיל לספור מ-0, אז המיקום של התו 6 בעצם הוא המיקום של התו האחרון במחרוזת, ולכן אנחנו צריכים את הקוד length-1. אנחנו יכולים להשתמש בזה לדוגמא על מנת למצוא את האות הראשון בסדרה של מחרוזות ולסדר המחרוזות לפי סדר האלפבית.

+ +

מציאת חלק ממחרוזת וחילוצו

+ +
    +
  1. לפעמים נרצה לבדוק האם מחרוזת מסויימת בת מספר תווים נמצאת בתוך מחרוזת גדולה יותר. (באופן כללי אנחנו בודקים האם מחרוזת המשנה קיימת בתוך המחרוזת). ניתן לבצע זאת באמצעות מתודת {{jsxref("String.prototype.indexOf()", "indexOf()")}} אשר מקבלת {{glossary("parameter")}} אחד — את מחרוזת המשנה שאנחנו נרצה לחפש בתוך המחרוזת הגדולה יותר. נסו להזין את הקוד הבא: + +
    browserType.indexOf('zilla');
    + קיבלנו בחזרה את הערך 2 שמציין שמחרוזת-המשנה "zilla" מתחילה במיקום 2 בתוך המחרוזת "mozilla". קוד שכזה יכול לעזור לנו לסנן מחרוזות. לדוגמא, אם יש לנו רשימה של כתובות אינטרנט, ונרצה לסנן רק את אלו המכילים את המחרוזת "zilla".
  2. +
+ +
    +
  1. שימו לב שניתן לבצע סינון זאת גם על דרך השלילה אשר תהיה כמובן יעילה יותר. נסו את הקוד הבא: +
    browserType.indexOf('vanilla');
    + קוד זה יחזיר  לנו את התוצאה 1- אשר משמעותה היא כי מחרוזת המשנה שהזנו למתודה לא קיימת במחרוזת הראשית. כאן לדוגמא, המחרוזת 'vanilla' לא נמצאה במחרוזת הראשית.
    +
    + אנו יכולים לעשות בזה שימוש למצוא את כל המופעים של מחרוזות שכן מכילים את מחרוזת המשנה 'mozilla' או שאינם מכילים, אם אנחנו משתמשים באופרטור שלילה כפי שמצויין למטה. + +
    if(browserType.indexOf('mozilla') !== -1) {
    +  // do stuff with the string
    +}
    +
  2. +
  3. כשאנחנו יודעים היכן מחרוזת המשנה שלנו מתחילה בתוך מחרוזת ראשית, ואנחנו יודעים באיזה תו אנחנו רוצים שמחרוזת המשנה תסתיים, אנחנו יכולים להשתמש ב - {{jsxref("String.prototype.slice()", "slice()")}} נסו להזין את הקוד הבא: +
    browserType.slice(0,3);
    + קוד זה יחזיר לנו כתוצאה "moz" - הארגומנט הראשון שהזנו - 0 - הוא המיקום של התו הראשון במחרוזת המשנה שנרצה לחלץ, והארגומנט השני שהזנו - 3 - יהיה התו שאחרי התו האחרון במחרוזת שנרצה לחלץ. זאת אומרת, החיתוך של המחרוזת מתרחש החל מהתו הראשון ועד, אך לא כולל, התו הרביעי. להזכירכם - מחשבים מתחילים לספור מ-0 ולא מ-1.
    +  
  4. +
  5. בנוסף, אם נרצה לחלץ את כל התווים אחרי תו מסויים, אנחנו יכולים להשמיט את הארגומנט השני. כלומר אנחנו ניתן למתודה רק את מיקום התו שאיתו נתחיל את החילוץ. ראו את הקוד הבא: +
    browserType.slice(2);
    + קוד זה מחזיר את הערך "zilla" - מכיוון שהאות שבמיקום 2 היא האות z ומכיוון שהשמטנו את הארגומנט השני, המתודה חילצה את כל התווים עד סוף המחרוזת browserType.
  6. +
+ +
+

להזכירכם: הפרמטר השני של ()slice הוא אופציונלי: אם נשמיט אותו, החיתוך יסתיים בסוף המחרוזת המקורית. יש גם אופציות נוספות. ראו בדף בנושא {{jsxref("String.prototype.slice()", "slice()")}} ללמוד על הנושא יותר.

+
+ +
+

להזכירכם: מתודות ומאפיינים אלו לא שומרות את התוצאה של המניפולציה או החישוב שהן ביצעו. על מנת לשמור את התוצאה, אנחנו צריכים לשמור אותה במשתנה חדש. כמו כן, שימו לב שמתודות ומאפיינים אלו לא שינו את מחרוזת המקור שעליה ביצענו את החישובים/מניפולציות השונות.

+
+ +

שינוי אות גדולה לאות קטנה, וההיפך

+ +

המתודות של מחרוזת {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} ו- {{jsxref("String.prototype.toUpperCase()", "toUpperCase()")}} מאפשרות להמיר מחרוזת בשלמותה לאותיות גדולות או לאותיות קטנות, בהתאמה. זה יכול להיות מאוד שימוש כשנרצה לנרמל את כל הערכים שהמשתמש מכניס לפני שנעביר לשרת. להזכירכם - JavaScript היא case sensitive.

+ +

נסו להכניס את הקוד הבא וראו מה התוצאה:

+ +
let radData = 'My NaMe Is MuD';
+radData.toLowerCase();
+radData.toUpperCase();
+ +

נסו לבדוק מה הערך של המשתנה radData והאם מתודות אלו שמרו בו את התוצאה של הפעלתן.

+ +

עדכון חלקים של מחרוזת

+ +

אנחנו יכולים להחליף מחרוזת אחת במחרוזת אחרת באמצעות המתודה {{jsxref("String.prototype.replace()", "replace()")}}. מתודה זו עובדת בצורה פשוטה וברורה, למרות שניתן לבצע איתה דברים מורכבים יותר, אך לא ניכנס אליהם במדריך זה.

+ +

מתודה זו מקבלת 2 ארגומנטים/פרמטרים - הראשון הוא המחרוזת שאנחנו רוצים להחליף והשני הוא המחרוזת שתיכנס במקום. נסו את הדוגמא הבאה:

+ +
browserType.replace('moz','van');
+ +

שימו לב שגם הפעם הערך שמוחזר לנו הוא המחרוזת החדשה שבוצעה בה ההחלפה, אך הערך הזה לא נשמר במחרוזת שעליה עשינו את ההחלפה. על מנת לקבל את המחרוזת החדשה במשתנה שלנו browserType אנחנו נצטרך לקבוע שהערך שלו יהיה התוצאה של ההפעלה של מתודה זו. כלומר - browserType = browserType.replace('moz','van');

+ +

דוגמאות ללמידה עצמאית

+ +

בחלק זה אנחנו נדריך אתכם לבצע כמה מניפוליות וחישובים על מחרוזות. בכל תרגיל המפורט למטה, יש לנו כמה מערכים של מחרוזות, ולולאה שמחשבת את הערך של כל איבר במערך ומציגה אותו ברשימה. אתם לא צריכים להבין כרגע מערכים או לולאות - אלו יוסברו בהמשך המדריך. אתם צריכים לכתוב בכל תרגיל קוד שיציג את התוצאה של המחרוזות הללו, בהתאם לתרגיל.

+ +

כל דוגמא מגיע עם כפתור "Reset" על מנת לאתחל את הקוד במידה והוא השתבש וכן כפתור "Show solution" על מנת להציג את פתרון אפשרי במקרה ונתקעתם.

+ +

סינון של הודעות

+ +

בתרגיל זה אנחנו מתחיל בתרגיל פשוט - יש לנו מערך של הודעה ברכה, אבל אנחנו רוצים למיין ולסנן רק את אלו שמכילות הודעה ברכה בהקשר של כריסמס. אנחנו רוצים שתכתוב משפט תנאי בתוך הקוד ( ... )if אשר יבדוק כל מחרוזת וידפיס אותה לרשימה רק אם היא מכילה ברכה של כריסמס.

+ +
    +
  1. חשבו תחילה איך אנחנו יכולים לבדוק האם ההודעה בכל פעם היא הודעה הקשורה לכריסמס. איזה מחרוזת מוצגת בכל ההודעות האלו ואיזו מתודה יכולה לבדוק האם המחרוזת נמצאת בתוך ההודעה הזו (אשר גם היא מחרוזת).
  2. +
  3. אנחנו נלמד לכתוב משפט תנאי בתצורת operand1 operator operand2. האם הערך הנמצא מצד שמאל שווה לערך הנמצא מצד ימין? האם תוצאת הפעלת המתודה מצד שמאל, תהא שווה לערך בצד ימין לצד ימין? רמז - במקרה הנוכחי יהיה עדיף לבדוק האם תוצאת הפעלת המתודה בצד שמאל שונה מהערך בצד ימין.
  4. +
+ + + +

{{ EmbedLiveSample('Playable_code', '100%', 590, "", "", "hide-codepen-jsfiddle") }}

+ +

שינוי אותיות גדולות וקטנות

+ +

בתרגיל זה יש לנו שמות של ערים בבריטניה, אך יש ערבוב של אותיות גדולות וקטנות בשמות הערים. אנחנו רוצים שתשנו את המחרוזות כך שכולן יהיו עם אותיות קטנות, למעט האות הראשונה שתהיה אות גדולה. דרך מומלצת לעשות זאת:

+ +
    +
  1. החליפו את כל המחרוזת שנמצאת משתנה input למחרוזת עם אותיות קטנות ואחסנו את התוצאה במשתנה חדש.
  2. +
  3. נסו לקבל את האות הראשונה של המחרוזת המאוחסנת במשתנה החדש שיצרתם ואחסנו את האות הראשונה במשתנה חדש נוסף.
  4. +
  5. השתמשו במשתנה זה כמשתנה המכיל את מחרוזת המשנה והחליפו את האות הראשונה לאות גדולה. אחסנו את התוצאה של ההחלפה במשתנה חדש.
  6. +
  7. שנו את הערך של המשתנה result כך שייה שווה לתוצאה הסופית ולא input.
  8. +
+ +
+

רמז: הפרמטרים של מתודות של מחרוזות לא חייבים להיות מחרוזות מפורשות אלא הם יכולים להיות גם משתנים וגם משתנים שמופעלים עליהן מתודות נוספות.

+
+ + + +

{{ EmbedLiveSample('Playable_code_2', '100%', 550, "", "", "hide-codepen-jsfiddle") }}

+ +

חילוץ וחיבור מחרוזות

+ +

בתרגיל זה, יש לנו מערך שכולל מס׳ מחרוזות המכילות מידע על תחנות רכבת באנגליה. המחרוזות הן פריטי מידע המכילים 3 אותיות עם קוד התחנה, לאחר מכן מידע ממוחשב כלשהו ולאחריו הסימן ; ולאחר מכן שם התחנה. לדוגמא:

+ +
MAN675847583748sjt567654;Manchester Piccadilly
+ +

אנו רוצים שתחלצו את קוד התחנה ואת שם התחנה, ותאחסנו אותה במחרוזת חדשה במבנה הבא:

+ +
MAN: Manchester Piccadilly
+ +

אנו ממליצים לכם לבצע זאת בצורה הבאה:

+ +
    +
  1. חלצו את שלושת האותיות שהן קוד התחנה ואחסנו אותן במשתנה חדש.
  2. +
  3. מצאו את האינדקס (מיקום) של התו ;.
  4. +
  5. חלצו את שם התחנה באמצעות האינדקס של תו ; כנקודת התחלה ואחסנו את התוצאה במשתנה חדש.
  6. +
  7. אחדו בין שני המשתנים ביחד עם מחרוזת רגילה למחרוזת אחת שלמה.
  8. +
  9. שנו את הערך של משתנה  result שיהיה שווה לערך של המחרוזת החדשה ולא של input.
  10. +
+ + + +

{{ EmbedLiveSample('Playable_code_3', '100%', 585, "", "", "hide-codepen-jsfiddle") }}

+ +

לסיכום

+ +

היכולת שלנו לטפל בטקסט בדרכים שונות במהלך כתיבת הקוד שלנו היא חשובה מאוד וחשוב לשלוט בה - במיוחד ב - JavaScript שכן אתרי האינטרנט ויישומי האינטרנט נועדו לתקשורת בין אנשים. מאמר זה נועד להעניק לכם את הבסיס שאתם צריכים לדעת על מניפולציות של מחרוזת לעת עתה ויסייע לכם כשניכנס לדברים קצת יותר מורכבים. המאמר הבא יעסוק בסוג האחרון מבין סוגי המידע שנעבור עליהם כרגע - מערכים.

+ +

{{PreviousMenuNext("Learn/JavaScript/First_steps/Strings", "Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}

+ +

במודול זה

+ + diff --git a/files/he/learn/javascript/first_steps/variables/index.html b/files/he/learn/javascript/first_steps/variables/index.html new file mode 100644 index 0000000000..3bed3e5bb3 --- /dev/null +++ b/files/he/learn/javascript/first_steps/variables/index.html @@ -0,0 +1,333 @@ +--- +title: אחסון המידע שאנחנו צריכים - משתנים וקבועים +slug: Learn/JavaScript/First_steps/Variables +translation_of: Learn/JavaScript/First_steps/Variables +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps")}}
+ +

לאחר קריאת המאמרים הקודמים, אתם אמורים לדעת כבה מהי JavaScript ומה היא יכולה לעשות עבורנו, כיצד אנו משתמשים ביחד עם טכנולוגיות web אחרות ומה המאפיינים העיקריים שלה ממעוף הציפור. במאמר זה אנחנו ניכנס לעומק של הבסיס של השפה ונסתכל על אחד מאבני הבניין של השפה - משתנים.

+ + + + + + + + + + + + +
ידע מוקדם:הבנה בסיסית של מחשב, הבנה בסיסית של  HTML, CSS ו - JavaScript.
מטרה:לקבל הכרות עם הבסיס של המשתנים.
+ +

כלים נדרשים

+ +

לאורך מאמר זה, תתבקשו להזין מספר שורות קוד בקונסולה על מנת לבדוק את ההבנה שלכם. אם אתם משתמשים בדפדפן במחשב, הדרך הכי טובה לבדוק את הקוד היא באמצעות הקונסולה של JavaScript. לפרטים נוספים אודות הקונסולה ראה What are browser developer tools.

+ +

מהו משתנה?

+ +

משתנה הוא קופסאת אחסון או קונטיינר, לערך מסויים. כמו שאנחנו עשויים להשתמש במספר על מנת לסכום, או במחרוזת על מנת להציג טקסט. משהו מיוחד בנוגע למשתנים הוא שהערכים שלהם יכולים להשתנות. נסתכל על הדוגמא הבאה:

+ +
<button>Press me</button>
+ +
const button = document.querySelector('button');
+
+button.onclick = function() {
+  let name = prompt('What is your name?');
+  alert('Hello ' + name + ', nice to see you!');
+}
+ +

{{ EmbedLiveSample('What_is_a_variable', '100%', 50, "", "", "hide-codepen-jsfiddle") }}

+ +

בדוגמא זו, לחיצה על הכפתור תריץ מספר שורות קוד. הקוד בשורה 4 מקפיץ הודעה על גבי המסך של המשתמש ומבקש ממנו להכניס את שמו ומאחסן את הערך שהוזן במשתנה שעונה לשם name. הקוד בשורה 5 מקפיץ לנו הודעה נוספת עם שמו של המשתמש, שנלקח מהערך של המשתנה name.

+ +

על מנת להבין מדוע זה שימושי כל כך, נסו לחשוב על דרך לרשום את הדוגמא הזו, מבלי להשתמש במשתנה. זה עלול להיראות כמו הקוד הבא:

+ +
let name = prompt('What is your name?');
+
+if (name === 'Adam') {
+  alert('Hello Adam, nice to see you!');
+} else if (name === 'Alan') {
+  alert('Hello Alan, nice to see you!');
+} else if (name === 'Bella') {
+  alert('Hello Bella, nice to see you!');
+} else if (name === 'Bianca') {
+  alert('Hello Bianca, nice to see you!');
+} else if (name === 'Chris') {
+  alert('Hello Chris, nice to see you!');
+}
+
+// ... and so on ...
+ +

אתם אולי לא מבינים עדיין את הסינטקס להצהרה על משתנה, אבל אתם מבינים את הרעיון - אם לא היו לנו משתנים, היינו צריכים לרשום כמויות עצומות של קוד, על מנת לבדוק האם השם אשר הוכנס על ידי המשתמש תואם למה שהגדרנו ואז להציג את ההודעה המתאימה. ברור ששימוש באופציה זו אינו יעיל בשום צורה ופשוט לא יעבוד שכן לא ניתן להכניס את האפשרויות בעולם.

+ +

קיומם של משתנים הוא הגיוני ונדרש, וככל שנלמד יותר לעומק JavaScript אנחנו נתרגל לשימוש בהם באופן טבעי.

+ +

דבר מיוחד נוסף לגבי משתנים הוא העובדה שהם יכולים להכיל כל דבר - לא רק מחרוזת או מספרים. משתנים יכולים להכיל גם מידע מורכב ואפילו פונקציות שלמות. נלמד על כך בהמשך.

+ +
+

לתשומת לב: אנחנו אומרים שמשתנים מכילים ערכים. זוהי אבחנה שחשוב לשים אליה. משתנים אינם ערכים בעצמם; הם רק קופסאות אחסון - קונטיינרים, בעבור ערכים. ניתן לדמיין זאת באמצעות התמונה הבאה:

+
+ +

+ +

Declaring a variable - הצהרה על משתנה

+ +

על מנת לעשות שימוש במשתנה, אנחנו קודם כל צריכים ליצור אותו, או יותר מדוייק, אנחנו צריכים להצהיר עליו. על מנת להצהיר על משתנה אנחנו צריכים להשתמש במילה השמורה var או במילה השמורה let ולאחריהן השם שנרצה לתת למשתנה:

+ +
let myName;
+let myAge;
+ +

כאן הצהרנו על שני משתנים שנקראים myName ו- myAge. נסו להזין את השורות האלו בקונסולה. לאחר מכן, נסו ליצור משתנה אחד או שניים בעצמכם.

+ +
+

לתשומת לב: ב- JavaScript, כל הוראת קוד (לא כל שורת קוד) צריכה להסתיים עם הסימן ; - אם לא נכניס סימן זה, הקוד רוב הסיכויים יעבוד, אבל אם נכניס מספר שורות קוד ביחד, כנראה שלא. אנא התרגלו להוסיף ; בעת שאתם כותבים את הקוד שלכם.

+
+ +

אתם יכולים לבדוק האם הערכים האלו קיימים בסביבת ההרצה על ידי הדפסה של שמות המשתנים לקונסולה כפי שמתואר להלן:

+ +
myName;
+myAge;
+ +

כרגע למשתנים אלו אין כל ערך. אנחנו רק הצהרנו עליהם ובכך הם נוצרו, אך הם כרגע מעין ״קופסאות ריקות״. כשאנחנו מזינים את שמות המשתנים בקונסולה, קיבלנו בקונסולה undefined. אם לא היינו מצהירים עליהם, היינו מקבלים הודעת שגיאה אחרת. נסו להבין מה ההבדל ביניהם.

+ +
scoobyDoo;
+ +
+

לתשומת לב: אל תבלבלו בין משתנה שקיים אך לא מכיל ערך לבין משתנה שלא קיים כלל. אם נחשוב עליהם כקופסאות אחסון, משתנה שהוצהר אך לא נתנו לו ערך יצר לנו קופסא לאחסון, אך לא אחסנו בו כלום. כלומר הקופסא קיימת אך ריקה. במקרה כזה נקבל את הערך undefined.

+ +

לעומת זאת, משתנה שלא הוצהר, זה כאילו לא יצרנו את קופסת האחסון מלכתחילה ולכן הודעת השגיאה שנקבל היא שהדפדפן לא מוצא את המשתנה, כלומר, הוא לא מוצא את קופסאת האחסון (כי לא יצרנו אותה).

+
+ +

השמת ערך למשתנה

+ +

ברגע שהצהרנו על משתנה, אנחנו יכולים לאתחל אותו עם ערך שנשים לו. אנחנו עושים זאת על ידי סימן ה-״שווה״ - =, ולאחריו הערך שאנחנו נרצה לשים במשתנה. לדוגמא:

+ +
myName = 'Chris';
+myAge = 37;
+ +

נסו להזין בקונסולה את הקוד הבא. אתם אמורים להראות שהערכים שהשמנו למשתנים מוחזרים לנו בקונסולה. שוב, אנחנו יכולים לקבל את הערך של משתנה על ידי הזנת שמו לקונסולה. ננסה זאת שוב:

+ +
myName;
+myAge;
+ +

ניתן להצהיר על משתנה וכן להשים לו ערך באותו זמן:

+ +
let myDog = 'Rover';
+ +

זו ככל הנראה תהיה הדרך שבה נרשום משתנים - הצהרה והשמה באותה שורה שכן זוהי דרך מהירה יותר מאשר לרשום הצהרה בשורה אחת והשמה של ערך בשורה אחרת.

+ +

ההבדלים בין var לבין let

+ +

בשלב זה אתם בטח שואלים ״מדוע צריכים שתי מילים שמורות על מנת להגדיר משתנים?״ או ״למה יש לנו גם את let וגם את var

+ +

הסיבות הן בעיקר היסטוריות. כאשר JavaScript רק נוצרה, היה קיים רק var. זה עבד במרבית המקרים, אבל היו לו סוגיות שונות בצורה ובדרך שבה הוא עבד. ההתנהגות שלו הייתה יכולה להיות מבלבלת וקצת מעצבנת. לכן, let נוצר בגרסאות מודרניות יותר של JavaScript, והציג מילה שמורה חדשה ליצירת משתנים, אשר פועלת בצורה אחרת מהמילה השמורה var ומתקנת את הסוגיות שהיו עם דרך ההגדרה הקודמת. סתם לידיעה - דרך זו של שימוש במילה השמורה let החלה בגרסת העדכון החשובה של JavaScript שנקראת ES2015 (ES6).

+ +

אנו נגע במספר הבדלים פשוטים ביניהם, אך לא ניגע בכולם כרגע. אנו נבין את ההבדלים ביניהם בהמשך ככל שניכנס יותר לעומק של השפה. אם תרצו להרחיב בנושא - היכנסו לקישור let reference page.

+ +

נתחיל בכך שאם נרשום מספר שורות קוד שבהן נצהיר על משתנה ונשים בו ערך. אנחנו יכולים להצהיר על משתנה באמצעות שימוש במילה var גם לאחר שהשמנו בו ערך והתוכנית עדיין תעבוד. כלומר, המשתנה יהיה מוכר לדפדפן. לדוגמא:

+ +
myName = 'Chris';
+
+function logName() {
+  console.log(myName);
+}
+
+logName();
+
+var myName;
+ +
+

לתשומת לב: קוד זה לא יעבוד כשננסה להכניס אותו שורה אחר שורה בקונסולה אלא רק כשנכניס את כל שורות קוד באמצעות JavaScript.

+
+ +

זה עובד בגלל מנגנון שנקרא Hoisting. אם תרצו להרחיב על כך, ראו קישור לפרטים נוספים על הנושא. בקצרה המשמעות שלו היא שב-JavaScript הצהרות על משתנים (והצהרות בכללי) מבוצעות לפני שיתר הקוד רץ, כלומר, הצהרה על משתנה במקום מסויים בקוד תהיה זהה להצהרה שלו בתחילת הקוד. יחד עם זאת, חשוב לשים לב שמנגנון זה משפיע רק על הצהרה של משתנים ולא על השמה של ערכים אליהם. הערכים שלהם יושמו אליהם בהתאם לסדר ריצת הקוד. 

+ +

Hoisting לא מתבצע יותר עם המילה השמורה let. אם נשנה את var ל- let בדוגמא למעלה, זה יציג לנו שגיאה. זה דבר טוב כמובן - הצהרה על משתנה לאחר שאנחנו משימים לו ערך גורמת לבלבול ולקושי בקריאה והבנה של הקוד.

+ +

בנוסף, כשאנחנו משתמשים ב- var, אנחנו יכולים להצהיר על המשתנה שיצרנו באמצעותו כמה פעמים שנרצה ואילו בעת שימוש ב- let אנחנו לא יכולים. הקוד הבא לדוגמא, יעבוד:

+ +
var myName = 'Chris';
+var myName = 'Bob';
+ +

אבל הקוד הבא יקפיץ לנו שגיאה בשורה השנייה:

+ +
let myName = 'Chris';
+let myName = 'Bob';
+ +

ולכן נצטרך לרשום אותו בצורה הבאה:

+ +
let myName = 'Chris';
+myName = 'Bob';
+ +

שוב, מדובר בכלל חשוב אשר נועד למנוע הצהרה חוזרת של משתנה. אנו ממליצים לבצע שימוש כמה שיותר ב- let מאשר ב-var . אין שום סיבה שנרצה להשתמש ב- var, אלא אם אנחנו צריכים לתמוך בגרסאות ישנות של אינטרנט אקספלורר (גרסאות ישנות אלו לא תומכות ב- let אלא רק החל מגרסה 11; הדפדפן אדג׳ לעומת זאת תומך במלואו ב-let).

+ +
+

לתשומת לב: אנחנו בשלבים של עדכון הדוגמאות בקורס זה לשימוש ב- let במקום var.

+
+ +

עדכון משתנה

+ +

ברגע שמשתנה הוצהר והושם לו ערך, אנחנו יכולים לשנות (או לעדכן) את הערך שנמצא באותו משתנה, פשוט על ידי השמה של ערך אחר. נסו להזין את הקוד הבא בקונסולה:

+ +
myName = 'Bob';
+myAge = 40;
+ +

מס׳ כללים בנוגע לשמות משתנים

+ +

אנחנו יכולים לקרוא למשתנים שלנו כמעט בכל שם שנרצה, אבל ישנן מס׳ הגבלות. באופן כללי, היצמדו לשימוש באותיות לועזיות (0-9, a-z, A-Z) ולתו מסוג קו תחתון.

+ + + +
+

לתשומת לב: ניתן למצוא את רשימת המילים השמורות של השפה ב- Lexical grammar — keywords.

+
+ +

דוגמא למתן שמות למשתני בצורה נכונה:

+ +
age
+myAge
+init
+initialColor
+finalOutputValue
+audio1
+audio2
+ +

דוגמא למתן שמות למשתני בצורה לא נכונה:

+ +
1
+a
+_12
+myage
+MYAGE
+var
+Document
+skjfndskjfnbdskjfb
+thisisareallylongstupidvariablenameman
+ +

מילים שמורות:

+ +
var
+Document
+
+ +

נסו ליצור מספר משתנים חדשים בהתאם לכללים שציינו למעלה.

+ +

סוגי משתנים

+ +

ישנם מס׳ סוגים של מידע שנוכל לאחסן במשתנים. בחלק הזה אנחנו נתאר אותם בקצרה. במאמרים הבאים אנו נלמד אותם לעומק.

+ +

Numbers - מספרים

+ +

אנחנו יכולים לאחסן מספרים כמשתנים, בין אם הם מספר שלם, כמו 30, או בין אם הם מספר עשרוני, כמו 2.456. ב- JavaScript אנחנו לא צריכים להצהיר על סוג המשתנה, בשונה מכמה שפות תכנות אחרות. כשאנחנו נותנים למשתנה ערך מסוג מספר, אנחנו לא משימים את הערך בין גרשיים. לדוגמא:

+ +
let myAge = 17;
+ +

Strings - מחרוזות

+ +

מחרוזות אלו חלקים של טקסט. כאשר אנחנו נותנים למשתנה ערך של מחרוזת, אנחנו צריכים לעטוף את המחרוזת בגרשיים כפולות " " או בגרש בודד ' ' אחרת JavaScript עלולה לנסות לפרש את הקוד כשם נוסף למשתנה. לדוגמא:

+ +
let dolphinGoodbye = 'So long and thanks for all the fish';
+ +

Booleans - בוליאנים

+ +

בוליאנים אלו ערכי אמת או שקר. משתנים שמכילים ערך בוליאני יכולים לקבל 2 ערכים: או ערך אמת true או ערך שקר false. לדוגמא:

+ +
let iAmAlive = true;
+ +

בפועל, אנחנו נשתמש במשתנה מסוג בוליאני בדרך הבאה:

+ +
let test = 6 < 3;
+ +

כאן ביצענו שימוש באופרטור ״קטן מ-״ (<) על מנת לבדוק האם 6 קטן מ-3. כפי שניתן לצפות, זה יחזיר לנו false מכיוון ש-6 לא קטן מ-3. נלמד יותר לעומק על אופרטורים אלו בהמשך הקורס.

+ +

Arrays - מערכים

+ +

מערך הוא בעצם אובייקט יחיד, המכיל מספר ערכים המתוחמים בתוך סוגריים מרובעות. נסו להכניס את הקוד הבא לתוך הקונסולה:

+ +
let myNameArray = ['Chris', 'Bob', 'Jim'];
+let myNumberArray = [10, 15, 40];
+ +

ברגע שהמערכים האלו מוצהרים, אנחנו יכולים לגשת לכל איבר במערך באמצעות ציון המיקום שלו במערך. נסו את הקוד הבא:

+ +
myNameArray[0]; // should return 'Chris'
+myNumberArray[2]; // should return 40
+ +

הסוגרים המרובעות מצביעות על האינדקס המתאים למיקום של האיבר שאנחנו רוצים שיוחזר. שימו לב שהמיקומים במערך מתחילים מ-0. כלומר, האיבר הראשון במערך הוא באינדקס 0.

+ +

נרחיב על מערכים במאמר בהמשך הקורס.

+ +

Objects - אובייקטים

+ +

בתכנות, אובייקט הוא מבנה של קוד שמדמה אובייקט בעולם האמיתי. הוא מייצג מעין קופסא המכילה מידע על הגובה שלו, הרוחב שלו, האורך שלו או מאפיינים נוספים. אנחנו יכולים לדוגמא לייצר אובייקט שידמה אדם, ואובייקט זה יכיל מידע על שמו, גובה, משקל, שפה מדוברת וכד׳.

+ +

הכניסו את הקוד הבא בקונסולה:

+ +
let dog = { name : 'Spot', breed : 'Dalmatian' };
+ +

על מנת לאחזר מידע המאוחסן באובייקט, השתמשו בקוד הבא:

+ +
dog.name
+ +

אנו לא נעמיק בנושא אובייקטים כעת - אנו נלמד לעומק את הנושא במאמר בהמשך.

+ +

השמת משתנים דינאמית

+ +

JavaScript היא שפה דינאמית. שלא כמו שפות אחרת, ב- JavaScript אנחנו לא צריכים לציין איזה סוג של מידע יאוסן בתוך המשתנה (מספרים, מחרוזות, מערכים וכד׳).

+ +

לדוגמא, אם אנחנו מצהירים על משתנה ונותנים לו ערך שעטוף בגרשיים, הדפדפן יתייחס אליו כמחרוזת:

+ +
let myString = 'Hello';
+ +

אם נכניס מספרים בתוך הגרשיים, הוא עדיין יהיה מחרוזת!

+ +
let myNumber = '500'; // oops, this is still a string
+typeof myNumber;
+myNumber = 500; // much better — now this is a number
+typeof myNumber;
+ +

נסו להכניס את הקוד שלמעלה לקונסולה שורה אחר שורה, וראו התוצאות. אתם תשימו לב שאתם משתמשים באופטור מיוחד שנקרא typeof - אופרטור זה מחזיר לנו את סוג הערך המאוחסן במשתנה שהעברנו לו. הפעם הראשונה שהרצנו את האופרטור הזה, הוא החזיר string, שכן באותה נקודה, המשתנה myNumber מכיל מחרוזת, '500'. בדקו מה הקונסולה תחזיר כשנזין את שתי השורות האחרונות.

+ +

Constants - קבועים

+ +

להרבה שפות תכנות יש את הקונספט של constant או קבוע — משתנה שברגע שהכנסו לו ערך, אותו ערך לא משתנה. ישנן הרבה סיבות מדוע נרצה להשתמש בהם, מסיבות אבטחה - (אם סקריפט של אתר אחר מנסה לשנות את הערכים זה עלול ליצור בעיות) עד לפתרון שגיאות של הקוד והבנה שלו (קשה יותר לשנות בטעות ערכים שלא אמורים להשתנות).

+ +

בשלביה המוקדים של השפה, קבועים לא היו קיימים. כעת יש בשפה קבועים ואנו משתמשים במילה השמורה const, על מנת להצהיר עליהם ולהשים בערך ערך שלא ישתנה:

+ +
const daysInWeek = 7;
+const hoursInDay = 24;
+ +

const עובד בדיוק כמו let, למעט העובדה שאנחנו לא יכולים לתת ל- const ערך חדש. בדוגמא הבאה, השורה השנייה תציג לנו שגיאה בקונסולה:

+ +
const daysInWeek = 7;
+daysInWeek = 8;
+ +

לסיכום

+ +

במאמר זה למדנו אודות משתנים - מהם, כיצד ליצור אותם ומה ההבדל בינם לקבועים. במאמר הבא אנחנו נלמד אודות מתמתיקה בסיסית ב-JavaScript.

+ +

{{PreviousMenuNext("Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps/Maths", "Learn/JavaScript/First_steps")}}

+ +

במודול זה

+ + diff --git a/files/he/learn/javascript/first_steps/what_is_javascript/index.html b/files/he/learn/javascript/first_steps/what_is_javascript/index.html new file mode 100644 index 0000000000..4ad34985e7 --- /dev/null +++ b/files/he/learn/javascript/first_steps/what_is_javascript/index.html @@ -0,0 +1,447 @@ +--- +title: מה זה JavaScript? +slug: Learn/JavaScript/First_steps/What_is_JavaScript +tags: + - API + - JavaScript + - דרכים להוסיף JavaScript לדף + - הסבר על JavaScript + - מדריך + - מה זה JavaScript? + - מתחילים +translation_of: Learn/JavaScript/First_steps/What_is_JavaScript +--- +
{{LearnSidebar}} 
+ +
{{NextMenu("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps")}}
+ +

ברוך הבא לקורס JavaScript למתחילים של MDN. במאמר זה נסתכל על JavaScript ממעוף הציפור, ונענה על שאלות כגון ״מה זה JavaScript?״ ״מה ניתן לבצע איתה?״ ונוודא שאתם מרגישים בנוח עם מטרתה. 

+ + + + + + + + + + + + +
Prerequisites:ידע בסיסי בשימוש במחשב וכן הבנה בסיסית של HTML ו-CSS.
Objective:להכיר מעט את JavaScript, מה היא יכולה לעשות, ואיך היא קשורה לאתר אינטרנט.
+ +

הגדרה ממבט על

+ +

JavaScript היא שפת תכנות (שפת סקריפט) אשר מאפשרת לכם ליישם דברים מורכבים על גבי דפי האינטרנט - בכל פעם שדף אינטרנט מבצע משהו דינאמי כגון עדכון תכנים באופן עיתי, הצגת מפה אינטרקאטיבית, אנימציות שונות דו ותלת מימדיות וכד׳ (בניגוד לדף אינטרנט סטטי שרק מציג תוכן ללא שינוי כלשהו בדף), ניתן להיות בטוח ש JavaScript לוקחת בכך חלק. JavaScript היא החלק השלישי ב-״עוגת״ טכנולוגיות ה-web כאשר את שתי הטכנולוגיות האחרות למדנו בחלקים אחרים של איזור הלמידה (HTML and CSS).   

+ +

+ + + +

שלושת השפות בנויות כשכבות אחת על גבי השנייה, כפי שניתן לראות באיור למעלה. ננסה להבין זאת באמצעות טקסט פשוט. נסמן את הטקסט באמצעות HTML, על מנת לתת לו מבנה ומטרה. בדוגמא הנוכחית למטה, סימנו את הטקסט באלמנט מסוג פסקה <p>.

+ +
<p>Player 1: Chris</p>
+ +

+ +

לאחר מכן, נוסיף כמה כללי CSS  על מנת לעצב את האלמנט בצורה מסויימת:

+ +
p {
+  font-family: 'helvetica neue', helvetica, sans-serif;
+  letter-spacing: 1px;
+  text-transform: uppercase;
+  text-align: center;
+  border: 2px solid rgba(0,0,200,0.6);
+  background: rgba(0,0,200,0.3);
+  color: rgba(0,0,200,0.6);
+  box-shadow: 1px 1px 2px rgba(0,0,200,0.4);
+  border-radius: 10px;
+  padding: 3px 10px;
+  display: inline-block;
+  cursor: pointer;
+}
+ +

+ +

לבסוף, נוסיף קוד JavaScript על מנת להעניק דינאמיות והתנהגות מסוימת:

+ +
const para = document.querySelector('p');
+
+para.addEventListener('click', updateName);
+
+function updateName() {
+  let name = prompt('Enter a new name');
+  para.textContent = 'Player 1: ' + name;
+}
+
+ +

{{ EmbedLiveSample('A_high-level_definition', '100%', 80, "", "", "hide-codepen-jsfiddle") }}

+ +

נסו ללחוץ על הגרסה האחרונה של הטקסט וראו מה קורה.אתם יכולים למצוא את קוד המקור כאן, או דף אינטרנט.

+ +

JavaScript יכולה לבצע הרבה יותר - נעמיק בכך בהמשך הלמידה.

+ +

אז מה ניתן לבצע עם JavaScript?

+ +

הבסיס של JavaScipt מכיל כמה ממאפייני התכנות הנפוצים, אשר מאפשרים לנו לבצע פעולות כגון: 

+ + + +

דבר מעניין נוסף הוא הפונקציונליות אשר בנויה על גבי הבסיס של שפת JavaScript. אותם API (Application Programming Interfaces ) מעניקים לנו אפשרויות משמעותיות אשר נוכל להשתמש בהם כאשר אנו כותבים את קוד ה-JavaScript שלנו. API בתרגום לעברית זה ״ממשק תכנות יישומים״.  

+ +

API אלו חלקי קוד מוכנים אשר מאפשרים לנו כמפתחים להטמיע תוכניות אשר בצורה אחרת היה קשה מאוד להטמיע או אף בלתי אפשרי. הם מאפשרים לנו את הנוחות בתכנות, כפי שרהיטים מוכנים להרכבה (לדוגמא: איקאה) מאפשרים את הנוחות (המסויימת) בעיצוב דירה. הרבה יותר נוח לקחת סט מוכן להרכבה של מדף המכיל פלטת עץ מוכנה, עם ברגים ומעמד על מנת ליצור מדף קיר, מאשר להתחיל מהבסיס: למצוא את העץ המתאים, לחתוך אותו לגודל המתאים, למצוא את הברגים המתאימים ועוד. 

+ +

באופן כללי, API מחולקים לשתי קטגוריות:

+ +

+ +

API של הדפדפן (Browser APIs) - אלו API מובנים בתוך דפדפן האינטרנט, ומאפשרים לקבל מידע/נתונים מסביבת העבודה של המשתמש או לבצע דברים שימושים מורכבים. לדוגמא: 

+ + + +
+

לתשומת לב: הרבה מהדוגמאות אשר הובאו למעלה, לא יעבדו בדפדפנים ישנים - במהלך הניסוי והטעיה במהלך הקורס, אנו נצטרך לעשות שימוש בדפדפנים מתקדמים על מנת לעשות שימוש בדוגמאות אלו. דפדפנים אלו יכולים להיות כרום, פיירפוקס, אדג׳, אופרה.

+ +

כמו כן, ככל ונתקדם בשלבי הפיתוח של הקוד, נצטרך לקחת בחשבון בדיקת תאימות לדפדפנים השונים יותר לעומק, על מנת שנוכל לאפשר ללקוח להשתמש בכל הפונקציונליות שהגדרנו. 

+
+ +

API של צד שלישי לא בנויים בתוך הדפדפן כברירת מחדל, ובעיקרון אנחנו נצטרך לקבל את הקוד והמידע שלהם ממקום אחר באינטרט. לדוגמא:

+ + + +
+

לתשומת לב: APIs אלו הם נושאים מתקדמים יחסית, ואנחנו לא נגע בהם במודול זה. ניתן למצוא מידע נוסף ב- Client-side web APIs module.

+
+ +

כמובן שיש עוד המון אפשרויות!, יחד עם זאת, כנראה שלאחר למידה כה קצרה של JavaScript, עדיין לא ניצור את פייסבוק או גוגל הבאים, אך ככל שנתקדם במדריך ונבין לעומק הבסיס, נתקדם בדרך הנכונה. 

+ +

מה JavaScript עושה על גבי דף האינטרנט?

+ +

כאן אנו נתחיל להסתכל על קוד, ובזמן שנעשה זאת, ננסה להבין מה קורה בפועל, כאשר JavaScript רצה בדף האינטרנט.

+ +

בוא נחזור בקצרה על מה בפועל קורה כשאנו מעלים דף אינטרנט בדפדפן. (דיברנו על כך במאמר כיצד CSS עובד).  

+ +

כאשר אנו מעלים דף אינטרנט בדפדפן, אנו מריצים את הקוד (HTML, CSS ו-JavaScript) בתוך סביבת הריצה (לשונית הדפדפן). ניתן לדמות את זה למפעל אשר מקבל אליו את חומרי הגלם (הקוד) ומייצר מכך מוצר מסויים (דף האינטרנט).

+ +

+ +

JavaScript מורצת על ידי מנוע JavaScript של הדפדפן עצמו, לאחר שה-HTML וה-CSS הורכבו והושמו בדף האינטרנט שלנו. דבר זה מאפשר לנו להבטיח שהמבנה והעיצוב של דף האינטרנט הושלם ונמצא במקומו בזמן ש-JavaScript תחל לרוץ. 

+ +

מכיוון ששימוש נפוץ ועיקרי ב-JavaScript הוא האפשרות להעניק דינאמיות ולשנות HTML ו-CSS באמצעות Document Object Model API, מדובר בדבר הכרחי על מנת לאפשר זאת, שכן אם JavaScript תרוץ לפני שרכיבי ה-HTML וכללי העיצוב של CSS נטענו במלואם, עלולים להתרחש שגיאות באותה דינאמיות שביקשנו להעניק באמצעות JavaScript.

+ +

אבטחה בדפדפן

+ +

לכל לשונית בדפדפן יש מעין ״סל״ או מתחם נפרד להרצת הקוד - בשפה מקצועית סלים או מתחמים אלו נקראים ״סביבות הרצה״ - זאת אומרת, שברוב המקרים, קוד בכל לשונית ירוץ באופן נפרד לחלוטין מלשוניות אחרות בדפדפן, ולא יוכל לגשת או להשפיע על הקוד בלשונית אחרת. דבר זה הינו דבר חשוב בהיבטי אבטחה - שכן אחרת, זה היה פותח אפשרות נוספות להאקרים לפרוץ לאתרים או לגנוב מידע. 

+ +
+

לתשומת לב: יש דרכים להעביר קוד ומידע בין אתרים/לשוניות שונות בצורה בטוחה, אך נושאים אלו הינם מתקדמים ולא נדון בהם בקורס זה.

+
+ +

סדר הריצה של JavaScript 

+ +

כאשר הדפדפן נתקל בבלוק של קוד JavaScript, באופן כללי הוא יריץ את הקוד מלמעלה למטה. המשמעות היא שצריך לשים לב לסדר שבו אנו רושמים את הקוד. לדוגמא, בוא נחזור לבלוק הקוד שראינו בדוגמא הקודמת:

+ +
const para = document.querySelector('p');
+
+para.addEventListener('click', updateName);
+
+function updateName() {
+  let name = prompt('Enter a new name');
+  para.textContent = 'Player 1: ' + name;
+}
+ +

שורה 1: בקוד זה אנחנו בעצם מגדירים משתנה מסוג const (נרחיב עליו בהמשך) וקוראים לו בשם para, ובאמצעות ה-DOM אנחנו בוחרים את האלמנט HTML הראשון מסוג p.

+ +

שורה 2: אנו מצמידים למשתנה שהגדרנו מתודה בשם event listener (נרחיב על כך בהמשך) שבעצם ״תקשיב״ כאשר יתרחש אירוע מסוג לחיצה על ה-para, כלומר, על האלמנט p, קוד בלוק שנקרא updateName ירוץ. בלוק קוד זה הניתן לשימוש חוזר נקרא ״פונקציה״ והוא מוגדר בשורות 5-8. 

+ +

שורות 5-8: הגדרה של הפונקציהupdateName. פונקציה זו מבקשת מהמשתמש להכניס את שמו ומשנה את התוכן של para לשמו של המשתמש ביחד עם המחרוזת ״:Player 1״. 

+ +

אם נשנה את הסדר של שורות הקוד, לדוגמא, נחליף בין שורות 1 ו-3, אנו נקבל שגיאה בקונסולה של הדפדפן מסוג:  TypeError: para is undefined. זה אומר שכאשר אנו מבצעים להוסיף את  event listener- האובייקט para עדין לא קיים ולכן לא נוכל להוסיף לו event listener.

+ +
+

לתשומת לב: זוהי שגיאה מאוד נפוצה - חשוב לשים לב שהאובייקטים שאנו מנסים לגשת אליהם קיימים בטרם אנו מנסים לעשות איתם פעולות כלשהן. 

+
+ +

קוד מהודר מול קוד מפורש

+ +

יכול להיות שנתקלתם במושגים כגון שפה מפורשת או שפה מקומפלת/מהודרת בהקשר של תכנות ופיתוח תוכנה.

+ +

בשפות שהינן שפות ״מפורשות״, הקוד רץ מלמעלה למטה, והתוצאה של הרצת הקוד תוחזר במיידי, אנו לא צריכים לעשות טרנספורמציה כלשהי לקוד או שינוי שלו לתבנית אחרת לפני שהדפדפן יריץ אותו. 

+ +

לעומת זאת, שפות ״מקומפלות״ או שפות ״מהודרות״ נדרשות לבצע שינוי כלשהו לתבנית אחרת לפני שהן יוכלו לרוץ על ידי המחשב. לדוגמא,  C/C++ מקומפלות לשפת assembly לפני הרצה על ידי המחשב. 

+ +

JavaScript היא שפה קלת-משקל ומעין מפורשת (בפועל, כן מבוצע קימפול, אך לא נרחיב על הנושא). לשני סוגי השפות יש יתרונות, אך לא נדון בהם כרגע. 

+ +

קוד צד-לקוח מול קוד צד-שרת

+ +

ככל הנראה נתקלת במושגים קוד צד-לקוח (client-side) וקוד צד-שרת (server-side), במיוחד בהקשר של פיתוח Web. קוד צד-לקוח הוא קוד שרץ על גבי המחשב של המשתמש - כאשר צופים בדף אינטרנט, קוד צד-לקוח של דף האינטרנט יורד, מורץ ומוצג על ידי הדפדפן. במודול זה אנו נגע בעיקר ב- JavaScript של צד-לקוח.

+ +

קוד צד-שרת מצד שני, ​​רץ על גבי השרת, והתוצאה שלו מורדת ומוצגת בדפדפן. דוגמאות לשפות פיתוח קוד צד-שרת כוללות בין היתר את PHP, Python, Ruby, ASP.NET וגם...JavaScript. כן, JavaScript יכולה לשמש גם כשפת פיתוח עבור צד-שרת. לדוגמא, בסביבת הפיתוח הפופולרית Node.js. ניתן להרחיב את הלמידה על JavaScript כשפת קוד-שרת בנושא הייעודי שלנו Dynamic Websites – Server-side programming

+ +

קוד דינאמי מול קוד סטאטי

+ +

המושג דינאמיות (dynamic) משמש הן לתיאור קוד צד-לקוח והן לתיאור קוד צד-שרת והוא מתייחס לאפשרות לעדכן את התצוגה של דף אינטרנט או יישום אינטרנט כך שיוצגו דברים אחרים בנסיבות אחרות ויווצר תוכן חדש ככל שנדרש. 

+ +

קוד צד-שרת יוצר באופן דינאמי תוכן חדש על גבי השרת, לדוגמא, מייצא מידע מתוך מאגר הנתונים, ואילו קוד צד-לקוח מייצר תוכן חדש בתוך הדפדפן של המשתמש, לדוגמא, יוצר טבלת HTML חדשה וממלא אותה בנתונים שביקשנו מהשרת, ואז מציג למשתמש את הטבלה על גבי דף האינטרנט.

+ +

המשמעות של דינאמיות היא מעט שונה בין צד לקוח לצד שרת, אך הן קשורות אחת לשנייה, ובדרך כלל, הן עובדות יחד. 

+ +

דף אינטרנט שאין לו שום דינאמיות או עדכוני תוכן מכונה כדף סטאטי - הוא מציג למשתמש את אותו תוכן כל הזמן.  

+ +

כיצד נוסיף JavaScript לדף האינטרנט שלנו?

+ +

JavaScript מוחלת על דף ה-HTML בדרך דומה לדרך שבה אנו מחילים את כללי ה-CSS.

+ +

בעוד ש-CSS משתמש באלמנט {{htmlelement("link")}} על מנת להחיל גיליונות עיצוב חיצוניים ובאלמנט {{htmlelement("style")}} על מנת להחיל גיליונות עיצוב פנימיים, JavaScript צריכה אלמנט אחד - {{htmlelement("script")}}. נבין לעומק כיצד זה עובד: 

+ +

Internal JavaScript (כאלמנט בתוך קובץ ה-HTML)

+ +
    +
  1. אנא צרו העתק על גבי המחשב שלך של קובץ הדוגמא שלנו:  apply-javascript.html.
  2. +
  3. פתחו את הקובץ בדפדפן ובעורך הקוד. אתם תראו ש-HTML יצר דף אינטרנט פשוט המכיל כפתור שניתן ללחוץ עליו.
  4. +
  5. בעורך הקוד - הוסיפו את הקוד הבא בתוך ה-head, לפני התגית </head>:
  6. +
  7. +
    <script>
    +
    +  // JavaScript goes here
    +
    +</script>
    +
  8. +
  9. כעת, נוסיף קצת קוד JavaScript בתוך האלמנט {{htmlelement("script")}} על מנת שהדף יבצע משהו מעניין. לשם כך, הוסיפו את הקוד הבא מתחת לכיתוב:  " :JavaScript goes here line //״
  10. +
  11. +
    document.addEventListener("DOMContentLoaded", function() {
    +  function createParagraph() {
    +    let para = document.createElement('p');
    +    para.textContent = 'You clicked the button!';
    +    document.body.appendChild(para);
    +  }
    +
    +  const buttons = document.querySelectorAll('button');
    +
    +  for(let i = 0; i < buttons.length ; i++) {
    +    buttons[i].addEventListener('click', createParagraph);
    +  }
    +});
    +
  12. +
  13. שמרו את הקובץ ורעננו את הדפדפן - כעת אתם אמורים להבחין שכאשר אתם לוחצים על הכפתור, נוצרת כל פעם פסקה חדשה מתחת לפסקה הקודמת. 
  14. +
+ +
+

לתשומת לב: אם הדוגמא לעיל לא עובדת לכם, בדקו האם שמרתם את הקובץ בשם הנכון, האם יש לו סיומת html? האם הוספתם את האלמנט  {{htmlelement("script")}}  ישר לפני תגית הסגירה </head> ? להזכירכם, JavaScript היא case sensitive, וזה יכול להיות מאוד מסתכל. שימו לב לדקויות.

+
+ +
+

לתשומת לב: תוכלו לראות את הגרסה הזו גם ב- GitHub בקישור  apply-javascript-internal.html  או כדף אינטרנט.

+
+ +

External JavaScript (קישור קובץ JavaScript חיצוני)

+ +

הכנסת JavaScript בתוך קובץ ה-HTML עובד בסדר גמור, אך מה אם נרצה לשים את קוד ה-JavaScript בקובץ אחר? נראה כיצד עושים זאת. 

+ +
    +
  1. ראשית, צרו קובץ חדש באותה תיקיה שבו נמצא ה-HTML בשם script.js - וודאו שיש לו את סיומת הקובץ js על מנת שהוא יזוהה כ-JavaScript.
  2. +
  3. החליפו את האלמנט {{htmlelement("script")}}  עם האלמנט  {{htmlelement("script")}} : +
    <script src="script.js" defer></script>
    +
  4. +
  5. בתוך קובץ script.js, הוסיפו את הקוד הבא: +
    function createParagraph() {
    +  let para = document.createElement('p');
    +  para.textContent = 'You clicked the button!';
    +  document.body.appendChild(para);
    +}
    +
    +const buttons = document.querySelectorAll('button');
    +
    +for(let i = 0; i < buttons.length ; i++) {
    +  buttons[i].addEventListener('click', createParagraph);
    +}
    +
  6. +
  7. שמרו ורעננו את הדפדפן. זה עובד בדיוק אותו דבר כמו JavaScript פנימי, רק שכעת JavaScript נמצאת בקובץ חיצוני. באופן כללי, שמירת קוד JavaScript בקובץ חיצוני עדיפה בהיבט ארגון הקוד ושימוש חוזר שלו בכמה קבצי HTML. בנוסף, זה מאפשר לנו לקרוא את ה-HTML בצורה ברורה יותר.
  8. +
+ +
+

לתשומת לב: ניתן לראות את הגרסה הזו של הקוד בקישור  apply-javascript-external.html וכ-דף אינטרנט.

+
+ +

Inline JavaScript handlers (בתוך אלמנט ספציפי בקובץ ה-HTML)

+ +

תשומת לב כי לפעמים אנחנו ניתקל בקוד JavaScript שכתוב בתוך אלמנט ספציפי בקובץ ה-HTML.  זה נראה כך: 

+ +
+
function createParagraph() {
+  let para = document.createElement('p');
+  para.textContent = 'You clicked the button!';
+  document.body.appendChild(para);
+}
+ +
<button onclick="createParagraph()">Click me!</button>
+
+ +

ניתן את את הקוד הבא:

+ +

{{ EmbedLiveSample('inline_js_example', '100%', 150, "", "", "hide-codepen-jsfiddle") }}

+ +

לקוד זה יש את פונקציונליות זהה לקוד בשני החלקים הקודמים, כלומר, הוא מבצע בדיוק את אותו דבר, רק שאלמנט הכפתור - {{htmlelement("button")}}  מכיל בתוכו onclick  על מנת לאפשר לפונקציה לרוץ כשהכפתור נלחץ.

+ +

בבקשה לא לבצע שימוש בשיטה זו. זה נחשב ל-bad practice ״לזהם״ את קובץ HTML יחד עם JavaScript ולא יעיל, שכן בשיטה זו צריך להוסיף ()onclick=״createParagraph״ לכל אחד מהכפתורים שיהיו בדף. 

+ +

לעומת זאת, שימוש ב-JavaScript בלבד, מאפשר לנו לבחור את כל הכפתורים באמצעות קוד פשוט וקצר. לדוגמא: 

+ +
const buttons = document.querySelectorAll('button');
+
+for(let i = 0; i < buttons.length ; i++) {
+  buttons[i].addEventListener('click', createParagraph);
+}
+ +

ממבט ראשון זה אומנם נראה ארוך יותר מהאפשרות הראשונה, אך זה יעבוד לכל הכפתורים בדף, בכל כמות שהיא.

+ +
+

לתשומת לב: נסו לשנות קצת את הגרסה של  apply-javascript.html והוסיפו עוד כפתורים לקובץ. כשתרעננו את הדף, תראו שכל כפתור שנלחץ, יוצר פסקה. 

+
+ +

שיטות לטעינת סקירפטים (Script)

+ +

ישנן כמה סוגיות עם טעינה של סקריפטים באותו זמן. 

+ +

בעיה נפוצה היא שכל אלמנטי ה-HTML בדף מועלים בסדר שבה הם מוצגים/רשומים, מלמעלה למטה. אם אנחנו משתמשים ב-JavaScript על מנת לבצע מניפולציות באלמנטים על הדף (או יותר מדוייק, ב-DOM) הקוד שלנו לא יעבוד אם ה- JavaScript תיטען לפני שה-HTML שבו אנחנו מנסים לבצע מניפולציה ייטען בעצמו.

+ +

בדוגמאות למעלה, ה-JavaScript הפנימי וקובץ ה-JavaScript החיצוני נטענו ורצו בראש המסמך, לפני שה-HTML הועבר. זה יכול ליצור שגיאה. על מנת למנוע זאת כאשר אנחנו מוסיפים JavaScript בתור אלמנט script, הוספנו את הקוד הבא: 

+ +
document.addEventListener("DOMContentLoaded", function() {
+  ...
+});
+ +

זהו ״מאזין לאירוע״  - event listener, אשר ״מקשיב״ לאירוע של הדפדפן בשם ״DOMContentLoaded״. אירוע זה מעיד על כך שגוף ה-HTML, כל תוכן שנמצא בתוך תגית <body>  הועלה בשלמותו. כך, קוד JavaScript בתוך אותו בלוק לא ירוץ עד אשר האירוע יחל, ולכן השגיאה נמנעה. בהמשך הקורס, נרחיב על אירועים ומאזינים לאירועים. 

+ +

על מנת למנוע זאת כאשר אנחנו מוסיפים JavaScript באמצעות קובץ חיצוני, אנחנו משתמשים באפשרות יחסית חדשה של JavaScript, שהיא תכונה (attribute) בשם defer. שבעצם אומרת לדפדפן להמשיך לטעון את ה-HTML ברגע שהוא הגיע לתגית האלמנט <script>:

+ +
<script src="script.js" defer></script>
+ +

בשני המקרים, ה-HTML ייטען במקביל והקוד יעבוד. 

+ +
+

תשומת לב: במקרה של JavaScript הנטען מקובץ חיצוני, אנחנו לא השתמשנו באירוע DOMContentLoaded  מכיוון שתכונת ה-defer פתרה את הבעיה. יחד עם זאת, ניתן להשתמש ב-defer ב-JavaScript חיצוני בלבד. 

+
+ +

דרך מקובלת (ואינה נדרשת יותר) לפתור את הבעיה הזו, הייתה לשים את אלמנט ה-script שלנו ישר מתחת לתגית הסגירה של body. כלומר ישר מתחת לתגית <body/>כך שראשית ייטען כל ה-body. הבעיה עם פתרון זה הוא שטעינה/העברה של הסקריפט חסום לחלוטין עד אשר ה-HTML DOM נטען באופן מלא. באתרים גדולים עם כמות גדולה של JavaScript, זה יכול ליצור בעית ביצועים אשר גורמת להאטת האתר.

+ +

async and defer

+ +

בעיקרון יש  דרכים נוספות לעקוף את סוגיית חסימת הסקריפט - באמצעות — async and defer.

+ +

סקריפטים בעלי תכונה של async יורדו מבלי לחסום את הדף ויורצו ברגע שהסקריפט יסיים לרדת. אין בטחון שהסקריפטים ירוצו בסדר מסויים, אלא שהם פשוט לא יעצרו מיתר הדף מלהיות מוצג. דרך טובה להשתמש ב-async היא כאשר הסקריפטים בדף רצים באופן עצמאי אחד מהשני ולא תלויים בסקריפטים אחרים בדף.

+ +

לדוגמא:

+ +
<script async src="js/vendor/jquery.js"></script>
+
+<script async src="js/script2.js"></script>
+
+<script async src="js/script3.js"></script>
+ +

לא ניתן להסתמך על כך שהסקריפטים ירוצו בסדר שבה הם הועלו. הראשון עלול להיטען אחרי השני או השלישי, ובמקרה הזה, כל פונקציה לדוגמא אשר מוגדרת באותם סקריפטים ותלויה בקובץ הראשון, תציג שגיאה כי הקובץ הראשון לא מוגדר בזמן שהסקריפט השני או השלישי רץ.

+ +

defer לעומת זאת, גורמת לכך שהסקריפטים ירוצו בסדר שבה הם מוצגים על גבי הדף ותריץ אותם ברגע שהסקריפט והתוכן יורדו:

+ +
<script defer src="js/vendor/jquery.js"></script>
+
+<script defer src="js/script2.js"></script>
+
+<script defer src="js/script3.js"></script>
+ +

פה מה שיקרה הוא שכל הסקריפטים עם התכונה של defer ייטענו בסדר שבו הם מופיעים בדף. כך, אנחנו יכולים להיות בטוחים שהקובץ הראשון ייטען במלואו לפני שהקובץ השני יתחיל לרוץ וכך הלאה. 

+ +

לסיכום:

+ + + +

הערות ב-JavaScript

+ +

כמו בשפות HTML ו-CSS, גם ב-JavaScript  ניתן להוסיף הערות בקוד, אשר הדפדפן יתעלם מהן ונועדו על מנת לספק הוראות למפתחים אחרי כיצד הקוד עובד, וגם לכם, אפשרות לרענן את זכרונכם. הערות הן מאוד שימושיות, אנא בצעו בהם שימוש לעיתים קרובות, במיוחד עבור יישומים גדולים. 

+ +

יש שני סוגי הערות:

+ + + +

לדוגמא: 

+ +
// Function: creates a new paragraph and appends it to the bottom of the HTML body.
+
+function createParagraph() {
+  let para = document.createElement('p');
+  para.textContent = 'You clicked the button!';
+  document.body.appendChild(para);
+}
+
+/*
+  1. Get references to all the buttons on the page in an array format.
+  2. Loop through all the buttons and add a click event listener to each one.
+
+  When any button is pressed, the createParagraph() function will be run.
+*/
+
+const buttons = document.querySelectorAll('button');
+
+for (let i = 0; i < buttons.length ; i++) {
+  buttons[i].addEventListener('click', createParagraph);
+}
+ +
+

לתשומת לב: באופן כללי - יותר הערות בדרך כלל עדיף מקצת מדי הערות, אבל צריך לשים לב לא למצוא את עצמנו מוסיפים יותר מדי הערות שמסבירות מהן המשתנים שהגדרנו (במקרה כזה יהיה עדיף כבר להשתמש בשם הגיוני) או הערות שמסבירים פעולות פשוטות ומובנות בקלות. 

+
+ +

לסיכום

+ +

כעת עשינו את הצעד הראשון לתוך עולמה של JavaScript. התחלנו עם קצת תיאוריה על מנת להתחיל להתרגל להשתמש בה ולהבין מה הדברים שאנחנו יכולים לבצע איתה. בהמשך הדרך ראינו מספר דוגמאות קוד ולמדנו כיצד JavaScript משתלבת באתר האינטרנט שלנו, יחד עם רכיבים נוספים. 

+ +

JavaScript עלולה להיראות לנו קצת מלחיצה או לא ברורה בשלב זה, אבל אל דאגה, בקורס הזה אנחנו הולכים בצעדים קטנים אשר נבנים בצורה הגיונית. במאמר הבא אנחנו נעבור ליישום פרקטי ונתחיל בבניית דוגמאות JavaScript שלכם באופן עצמאי.

+ + + +

{{NextMenu("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps")}}

+ +

במודול זה

+ + diff --git a/files/he/learn/javascript/first_steps/what_went_wrong/index.html b/files/he/learn/javascript/first_steps/what_went_wrong/index.html new file mode 100644 index 0000000000..87d85d786c --- /dev/null +++ b/files/he/learn/javascript/first_steps/what_went_wrong/index.html @@ -0,0 +1,251 @@ +--- +title: מה השתבש? - פתרון שגיאות ב-JavaScript +slug: Learn/JavaScript/First_steps/What_went_wrong +translation_of: Learn/JavaScript/First_steps/What_went_wrong +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps")}}
+ +

כשבנינו את המשחק ״שחק את המספר״ במאמר הקודם, בטח שמתם לב שהוא לא עבד. מאמר זה לספק לכם הבנה כיצד למצוא שגיאות ב-JavaScript ולתקן אותן.

+ + + + + + + + + + + + +
ידע מוקדם:הבנה בסיסית של מחשב, הבנה בסיסית של  HTML, CSS ו - JavaScript.
מטרה: +

הכרת חלק מהאפשרויות ללתיקון שגיאות בקוד שלנו.

+
+ +

סוגי שגיאות

+ +

באופן כללי, כשאנחנו מבצעים משהו שגוי בקוד, יש שתי סוגי שגיאות עיקריות שאנחנו ניתקל בהן:

+ + + +

אוקיי, זה לא כזה פשוט — יש חלוקות נוספות של סוגי השגיאות, וככל ונעמיק בחומר ננחקור אותן לעומק. לצרוך הלימוד כרגע, החלוקה הזו תספיק בהתחלה. 

+ +

דוגמא לשגיאה

+ +

לשם התחלה, חזרו למשחק ״נחש את המספר״ שלנו - רק שהפעם, השתמשו בקובץ שלנו שהוכנסו בו מכלתחילה מספר שגיאות. כנסו ל-Github והכינו לעצמכם עותק מקומי של number-game-errors.html (ראו זאת בדף אינטרנט כאן).

+ +
    +
  1. לשם התחלה, פתחו את הקובץ המקומי בעורך הקוד ובדפדפן.
  2. +
  3. נסו לשחק עם המשחק, אתם תשימו לב כשאתם לוחצים על כפתור - "Submit guess", הכפתור לא עושה כלום.
  4. +
+ +
+

לתשומת לב: יכול להיות שהגרסה שאתם עבדתם עליה לא עובדת בעצמה, ואולי אותה תרצו לתקן. בכל מקרה, אנא השתמשו בגרסה שלנו לאורך המאמר הנוכחי, על מנת שתוכלו ללמוד את הטכניקות שאנחנו נלמד כאן. לאחר מכן, חזרו לדוגמא שלכם ונסו לתקן אותה אם היא אינה עובדת.

+
+ +

בשלב זה, ניעזר בקונסולה בדפדפן על מנת לראות את שגיאות הסינטקס, וננסה לתקן אותם. 

+ +

תיקון שגיאות סינטקס

+ +

בתחילת הקורס, הזנו מס׳ פקודות של JavaScript לתוך הקונסולה. יתרון נוסף של שימוש בקונסולה הוא העובדה שהקונסולה מחזירה לכם הודעות בדבר שגיאות כתיב כאשר אלו קיימות בקוד ה-JavaScript אשר נטען על ידי מנוע ה- JavaScript של הדפדפן. בוא נבדוק זאת:

+ +
    +
  1. לך ללשונית שבה יש את הקובץ number-game-errors.html פתוח ופתחו את הקונסולה. אתם אמורים לראות שגיאה שמכילה את המלל הבאה:
  2. +
  3. זו שגיאה דיי קלה לאיתור, והדפדפן מספק לם מס׳ נתונים על מנת לעזור לכם - צילום המסך לעיל לקוח מדפדפן Firefox אבל גם דפדפנים אחרים מספקים את אותו מידע. משמאל לימין, זו השגיאה: +
      +
    • ״x״ אדום אשר יעיד על כל שקיימת שגיאה.
    • +
    • הודעת שגיאה על מנת להראות שמשהו השתבש: "TypeError: guessSubmit.addeventListener is not a function".
    • +
    • טקסט וקישור "Learn More" אשר יוביל לדף MDN שמסביר מהי השגיאה - שימו לב שקישור זה קיים רק בפיירפוקס ולא בכרום.
    • +
    • השם של קובץ JavaScript אשר מקושר ללשונית ה-Debugger. אם נעקוב אחרי הקישור נראה את השורה המדויקת שבה התרחשה השגיאה.
    • +
    • מספר השורה שבה התרחשה השגיאה, ומספרו של התו באותה השורה שבו השגיאה נראתה לראשונה. במקרה שלנו, השגיאה התרחשה בשורה 86, ובתו מספר 3.
    • +
    +
  4. +
  5. אם נסתכל על שורה 86 בעורך הקוד שלנו, אנחנו נמצא את השורה הבאה: +
    guessSubmit.addeventListener('click', checkGuess);
    +
  6. +
  7. הודעת שגיאה זו אומרת ש-"guessSubmit.addeventListener is not a function", אז אנחנו כנראה אייתנו משהו בצורה לא נכונה. אם אנחנו לא בטוחים לגבי האיות הנכון של כתיב/סינטקס מסויים, הפתרון הכי טוב זה להסתכל על המאפיינים של הסינטקס באתר של MDN. הדרך הכי טובה לעשות זאת היא לחפש "mdn name-of-feature" במנוע החיפוש האהוב עליכם. הנה קישור לדוגמא לחסוך לכם זמן ()addEventListener.
  8. +
  9. אז, אם אנחנו מסתכלים על הדף, השגיאה הופיעה ככל הנראה מכיוון שאייתנו את שם המתודה לא נכון. זכרו ש- JavaScript היא case sensitive, וכל שינוי קטן באיות, או שימוש באותיות גדולות/קטנות לא בצורה נכונה, יגרום לשגיאה. שינוי של addeventListener לכתיב הנכון: addEventListener אמור לתקן את הבעיה.
  10. +
+ +
+

לתשומת לבכם ראו גם: TypeError: "x" is not a function. זהו דף שלנו שמסביר בפרטים על השגיאה הזו.

+
+ +

שגיאות סינטקס - דוגמאות נוספות

+ +
    +
  1. שמרו את הדף ורעננו אותו, אתם אמורים לראות שהשגיאה נעלמה.
  2. +
  3. כעת, אם המשתמש ינסה להכניס ניחוש וללחוץ על הכפתור של Submit, תתקבל שגיאה נוספת:
  4. +
  5. הפעם, השגיאה מדווחת עם ההודעה הבאה: "TypeError: lowOrHi is null", בשורה 78. +
    לתשומת לבכם: Null הוא ערך מיוחד שמשמעותו הוא ״כלום״ או ״ללא ערך״. כך lowOrHi אמנם הוצהר ואותחל, אבל הוא ללא כל ערך, אין לו סוג ואין ערך שהוזן לתוכו.
    + +
    לתשומת לבכם: שגיאה זו לא הופיעה ברגע שהדף נטען שכן שגיאה זו נמצאת בתוך פונקציה - בתוך () { ... }checkGuess. אנו נלמד על פונקציות במאמרים הבאים, ואנו נלמד שקוד אשר נמצא בתוך פונקציה רץ בסקופ (מתחם) אחר ונפרד מהסקופ שרץ בו קוד מחוץ לפונקציה. במקרה הנוכחי - הקוד שבתוך הפונקציה אשר גרם לשגיאה לא רץ עד אשר הפונקציה ()checkGuess לא הופעלה בשורה 26.
    +
  6. +
  7. :הסתכלו על הקוד בשורה 78 +
    lowOrHi.textContent = 'Last guess was too high!';
    +
  8. +
  9. שורה זו מנסה לקבוע את ה-property - מאפיין:  textContent של המשתנה lowOrHi למחרוזת טקסט, אך זה לא יעבוד מכיוון ש-lowOrHi לא מכיל את הערך שהוא אמור להכיל. בו ננסה לחפש מופעים נוספים של lowOrHi בקוד שלנו. הפעם הראשונה שנמצא אותו תהיה בשורה 48: +
    var lowOrHi = document.querySelector('lowOrHi');
    +
  10. +
  11. בשלב זה אנחנו מנסים להפוך את המשתנה שלנו להפנייה לאלמנט בדף ה-html, בוא ננסה לראות האם הוא מקבל את הערך null אחרי ההרצה של השורה הזו. הוסיפו את הקוד הבא לאחר שורה 49: +
    console.log(lowOrHi);
    + +
    +

    לתשומת לבכם: ()console.log מקבלת ארגומנט כלשהו ומדפיסה אותו לקונסולה. זוהי פונקציה מאוד שימושית לשם איתור שגיאות.

    +
    +
  12. +
  13. שמור ורענן, ואתה אמור לראות ש-()console.log החזירו את התשובה הבאה בקונסולה: אנו רואים שהערך של lowOrHiהוא בעצם null בנקודה זו ולכן הבעיה היא עם שורה 48.
  14. +
  15. ננסה לחשוב מהי הבעיה. שורה 28 משתמשת במתודה ()document.querySelector על מנת לקבל הפניה לאלמנט באמצעות בחירת סלקטור ה-CSS שלו. אם נסתכל בדף, אנחנו יכולים למצוא את האלמנט הרלוונטי: +
    <p class="lowOrHi"></p>
    +
  16. +
  17. כאן אנחנו רואים שאנחנו צריכים סלקטור של קלאס, אשר מתחיל עם (.), אבל הסלקטור שמועבר במתודה ()querySelector בשורה 48 אינו מכיל נקודה. זו יכולה להיות הבעיה, נסו לשנות את lowOrHi ל- .lowOrHi וראו מה קורה.
  18. +
  19. שמרו ורעננו את הדף ו-()console.log אמור להחזיר את האלמנט <p> שרצינו. 
  20. +
+ +
+

לתשומת לב: ראו גם TypeError: "x" is (not) "y" -  דף ההסבר שלנו לפרטים נוספים על שגיאה זו.

+
+ +

שגיאות סינטקס נוספות

+ +
    +
  1. אם תנסו לשחק עכשיו במשחק, אתם אמורים להצליח להתקדם יותר - אך עד שהמשחק יסתיים, בין אם ניחשתם את המספר האקראי הנכון ובין אם נגמרו לך הנסיונות.
  2. +
  3. כשהמשחק נגמר, אנחנו מקבלים שגיאה מסוג - "TypeError: resetButton.addeventListener is not a function"! אשר מופיעה בשורה 94.
  4. +
  5. אם נסתכל על שורה 94, נראה כי עשינו טעות באיות המתודה addEventListener ולכן נדרש לשנות את הקוד. להזכירכם, מתודות הן case senitive.
  6. +
+ +

טעות לוגית

+ +

בשלב זה, המשחק אמור לעבוד טוב, אך עם זאת, אחרי כמה משחקים, אתם תשימו לב שהמספר האקראי שלנו הוא תמיד 0 או 1. זה לא ממש מה שהתכוונו.

+ +

יש בוודאות שגיאה לוגית במשחק איפשהו, אך אנחנו לא מקבלים הודעת שגיאה, המשחק עובד, אך לא כמו רצינו.

+ +
    +
  1. נסו לחפש את המשתנה randomNumber ואת השורות בקוד שבהן אנחנו מגדירים אותו. הוא נמצא בשורה 44: + +
    var randomNumber = Math.floor(Math.random()) + 1;
    + והשורה שבה אנחנו מייצרים מספר אקראי חדש לאחר כל משחק היא בשורה 113:
  2. +
  3. +
    randomNumber = Math.floor(Math.random()) + 1;
    +
  4. +
  5. על מנת לבדוק האם השורות האלו הן הבעיתיות, אנחנו ניעזר ב- ()console.log ונכניס את הקוד הבא מתחת לשתי שורות לעיל: +
    console.log(randomNumber);
    +
  6. +
  7. שמרו ורעננו את הדף ותנסו לשחק מספר משחקים. אתם תראו ש- randomNumber שווה ל-1 בכל פעם שאנחנו מדפיסים אותו לקונסולה:
  8. +
+ +

מעבר על הלוגיקה של המשחק

+ +

על מנת לתקן זאת, בואו נחשוב כיצד שורה זו עובדת. קודם כל, אנחנו קוראים ל-()Math.random, אשר מייצרת מספר עשרוני בין 0 ל-1, לדוגמא: 0.5676665434:

+ +
Math.random()
+ +

לאחר מכן אנחנו מעבירים את התוצאה של הפעלת פונקציית ()Math.random דרך הפונקציה ()Math.floor, אשר בתורה, מעגלת את המספר ולאחר מכן מוסיפים 1. אם לא נוסיף 1, פונקציה זו יכולה לעגל כלפי מטה ואז נקבל 0.

+ +
Math.floor(Math.random()) + 1
+ +

1.  אנחנו צריכים להכפיל את המספר האקראי שלנו ב-100 לפני שנעביר אותו הלאה. זה ייתן לנו מספר אקראי בין 0 ל-99:

+ +
Math.floor(Math.random()*100);
+ +

הוספת של 1, תאפשר לנו לקבל ערך בין 1 ל-100:

+ +
Math.floor(Math.random()*100) + 1;
+ +

נסו לשמור ולרענן את הדף ואתם תראו שהמשחק עושה מה שהוא צריך לבצע - מייצר מספר אקראי בין 0 ל-100.

+ +

שגיאות נפוצות נוספות

+ +

ישנן שגיאות נפוצות נוספות שאנחנו ניתקל בהן: 

+ +

SyntaxError: missing ; before statement

+ +

שגיאה זו לרוב אומרת ששכחנו לשים ; בסוף שורות הקוד, אבל היא יכולה להיות גם מסיבה אחרת. אם נשנה את השורה שנמצאת בתוך הפונקציה ()checkGuess :

+ +
var userGuess = Number(guessField.value);
+ +

לקוד הבא:

+ +
var userGuess === Number(guessField.value);
+ +

זה יקפיץ לנו הודעת שגיאה מכיוון ש- JavaScript חושבת שאתה מנסה לבצע משהו אחר. צריך תמיד לוודא שאנחנו לא מערבבים בין סימן השווה שנועד להשים ערך (=) לבין שלושת סימני השווה שנועדו לבדוק האם ערך אחד שווה לשני, ולהחזיר true/false:

+ +
+

לתשומת לב: ראה גם SyntaxError: missing ; before statement דף ההסבר שלנו לפרטים נוספים על שגיאה זו.

+
+ +

המשחק תמיד נותן למשתמש לנצח, לא משנה מה הניחוש שהמשתמש הכניס

+ +

זה יכול להיות עוד סימן לכך שעירבבנו בין סימן ההשמה לבין סימן הבדיקה. לדוגמא, אם אנחנו את השורה הבאה שנמצא בתוך()checkGuess:

+ +
if (userGuess === randomNumber) {
+ +

לקוד הבא:

+ +
if (userGuess = randomNumber) {
+ +

תוצאת המבחן תהיה תמיד true, מה שגורם לכך שתמיד הניחוש של המשתמש נכון.

+ +

SyntaxError: missing ) after argument list

+ +

זוהי שגיאה פשוטה יחסית - היא אומרת באופן כללי ששכחנו לשים סוגריים בסוף קריאה לפונקציה או מתודה:

+ +
+

לתשומת לבד: ראה גם SyntaxError: missing ) after argument list  - דף ההסבר שלנו לפרטים נוספים על שגיאה זו.

+
+ +

SyntaxError: missing : after property id

+ +

שגיאה זו בדרך כלל מתייחסת לכך שלא יצרנו אובייקט ל JavaScript בצורה נכונה. נסה לשנות את הקוד הבא:

+ +
function checkGuess() {
+ +

לקוד הבא:

+ +
function checkGuess( {
+ +

זה גרם לדפדפן לחשוב שאנחנו מנסים להעביר את התוכן של הפונקציה כארגומנט של הפונקציה.

+ +

SyntaxError: missing } after function body

+ +

זו גם שגיאה פשוטה יחסית - היא אומרת בעיקרון ששכחנו אחת מהסוגריים המסולסלות במשפט תנאי שרשמנו. 

+ +

SyntaxError: expected expression, got 'string' or SyntaxError: unterminated string literal

+ +

שגיאות אלו אומרות באופן כללי ששכחנו להוסיף סימן של ' או ". בשגיאה הראשונה string יוחלף עם תו לא ידוע שהדפדפן ימצא במקום המרכאות או הגרש. השגיאה השניה אומרת שהמחרוזת לא הסתיימה עם גרש או מרכאות.

+ +
+

לתשומת לב: ראה גם SyntaxError: Unexpected token וגם SyntaxError: unterminated string literal  - דפי ההסבר שלנו לפרטים נוספים על שגיאות אלו.

+
+ +

לסיכום

+ +

כעת אנו יודעים את הבסיס להבין שגיאות בתוכניות JavaScript הפשוטות שלנו. רק צריך לזכור שזה לא יהיה תמיד קל להבין מה השתבש לנו בקוד. כאשר שגיאה מתרחשת, הסתכלו על מספר השורה שאתם מקבלים, ולכו לאותה שורה על מנת לנסות לאתר מה השתבש. זכרו תמיד שהשגיאה לא תמיד תהיה בשורה זו, ושאולי היא לא תהיה אחת מאלו שעברנו עליהם במאמר זה.

+ +

ראה גם

+ +
+ +
+ +

במודול זה

+ + diff --git a/files/he/learn/javascript/index.html b/files/he/learn/javascript/index.html new file mode 100644 index 0000000000..e606644330 --- /dev/null +++ b/files/he/learn/javascript/index.html @@ -0,0 +1,83 @@ +--- +title: JavaScript +slug: Learn/JavaScript +tags: + - JavaScript + - "JavaScript\_למתחילים" + - מדריך + - מדריך JavaScript + - מדריך javascript למתחילים + - מודול + - מתחיל + - נושא + - קידוד +translation_of: Learn/JavaScript +--- +
{{LearnSidebar}}
+ +

{{Glossary("JavaScript")}} הינה שפת תכנות אשר מאפשרת ליישם דברים מורכבים על גבי דפי האינטרנט. ברגע שדף האינטרנט עושה יותר מסתם להציג אינפורמציה סטטית — להציג עידכוני תוכן משתנים, מפות אינטרקטיביות או גרפים 2D/3D מונפשים, וכן הלאה — כנראה שJavaScript מעורב מאחורי הקלעים.

+ +

מסלול למידה

+ +

ניתן לטעון שJavaScript הינה מסובכת יותר ללימוד מאשר טכנולוגיות קשורות כמו HTML וCSS. לפני הניסיון ללמוד JavaScript, מומלץ מאוד לעשות היכרות לפחות עם שתי הטכנולוגיות המוזכרות, ואולי גם עם עוד טכנולוגיות. ניתן להתחיל בלעבוד על המודולים הבאים:

+ + + +

ניסיון קודם עם שפות תכנות אחרות יכול לעזור גם כן.

+ +

אחרי היכרות עם הבסיס של  JavaScript, הרמה שלכם אמורה להיות מספיק גבוהה בשביל לעבור ללמוד על נושאים מתקדמים, לדוגמא:

+ + + +

מודולים

+ +

נושא זה מכיל את המודולים הבאים, כאשר כל מודול מורכב ממספר מאמרים, מומלץ לעבור עליהם לפי הסדר המוצג.

+ +
+
צעדים ראשונים ב-JavaScript
+
במודול JavaScript הראשון שלנו, אנחנו קודם כל נענה על כמה שאלות בסיסיות כמו "מהי JavaScript?", "איך היא ניראת?" ו-"מה היא יכולה לעשות?", לפני שנתקדם לניסיון הפרקטי הראשון בכתיבת JavaScript. לאחר מכן נדון בכמה תכונות מפתח של JavaScript בפירוט, כגון משתנים, מחרוזות, מספרים ומערכים.
+
אבני הבניין של JavaScript
+
במודול זה, נגע באבני הבניין והמאפיינים הבסיסיים של JavaScript, נפנה את תשומת ליבנו לטיפוסים הנפוצים של בלוקי הקוד כמו משפטי תנאי, לולאות, פונקציות, ואירועים (Events). כבר ניתקלנו בדברים אלו בקורס, אך לא הרחבנו עליהם — במודול זה אנו נדון בכולם לעומק.
+
הכרות עם אובייקטים של JavaScript
+
ב-JavaScript, רוב הדברים הינם אובייקטים, מפיצ'רי הליבה של JavaScript כמו מחרוזות ומערכים עד לAPIים של הדפדפן הבנויים על גבי JavaScript. אתם יכולים אפילו לבנות אובייקטים בעצמכם כדי לעטוף פונקציות ומשתנים קשורים לחבילות אפקטיביות. חשוב להבין את העקרון של תכנות מונחה-העצמים של JavaScript אם אנחנו רוצים להתקדם עם הידע שלנו בשפה ולכתוב קוד יותר אפקטיבי, לכן סיפקנו את המודול הזה לעזור לכם. כאן נלמד את התאוריה והתחביר של אובייקט בפירוט, נראה איך יוצרים אובייקטים משלכם, ונסביר מה זה מידע בפורט JSON ואיך עובדים איתו ועם אובייקטים בכללי.
+
+ + + +
+
Asynchronous JavaScript
+
+

במודול זה אנחנו נסתכל על asynchronous JavaScript ונסביר את החשיבות של עקרון זה. כיצד אנחנו יכולים לבצע בכך שימוש על מנת לטפל באירועים מסויימים כמו קבלת מידע ומקורות משרת.

+
+
+ + + +
+
 Web API - צד לקוח
+
כאשר כותבים JavaScript עבור צד-לקוח לדפי אינטרנט או יישומי אינטרנט, כמעט מיד תתקלו בצורך להשתמש ב - API - אלו ממשקים עבור ביצוע מניפולציות של היבטים שונים של הדפדפן ומערכות ההפעלה שהאתר רץ עליהם, או אפילו מניפולציה לנתונים מאתרים או שירותים אחרים. במודול הזה אנו נחקור מהם API ואיך להשתמש בכמה מה-API הנפוצים שתפגשו בהם לעיתים קרובות במהלך עבודת הפיתוח. 
+
+ +

פתרון בעיות נפוצות ב - JavaScript

+ +

המאמר בנושא שימוש ב-JavaScript לפתרון בעיות נפוצות מספק קישורים לקטעי תוכן המסבירים איך להשתמש ב-JavaScript על מנת לפתור בעיות מאוד נפוצות בתהליך הפיתוח.

+ +

ראה בנוסף

+ + + +
+
JavaScript on MDN
+
נקודת הפתיחה הראשית לליבת התיעוד של JavaScript ב-MDN — כאן תמצאו תיעוד נרחב על כל ההיבטים של שפת JavaScript, וכמה הדרכות מתקדמות המכוונות למפתחי JavaScript מנוסים.
+
Coding math
+
סדרות של הדרכות וידאו מצויינות ללימוד המתמטיקה הנצרכת להפיכתכם למתכנתים אפקטיביים, מועבר על ידי Keith Peters.
+
diff --git a/files/he/learn/javascript/objects/adding_bouncing_balls_features/index.html b/files/he/learn/javascript/objects/adding_bouncing_balls_features/index.html new file mode 100644 index 0000000000..23197f00c4 --- /dev/null +++ b/files/he/learn/javascript/objects/adding_bouncing_balls_features/index.html @@ -0,0 +1,214 @@ +--- +title: Adding features to our bouncing balls demo +slug: Learn/JavaScript/Objects/Adding_bouncing_balls_features +translation_of: Learn/JavaScript/Objects/Adding_bouncing_balls_features +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Objects/Object_building_practice", "", "Learn/JavaScript/Objects")}}
+ +

במשימה זאת, אתה צריך להשתמש בכדורים הקופצים מהמאמר הקודם כנקודת התחלה ולהוסיף אליה כמה פיצ'רים חדשים ומעניינים.

+ + + + + + + + + + + + +
Prerequisites:Before attempting this assessment you should have already worked through all the articles in this module.
Objective:To test comprehension of JavaScript objects and object-oriented constructs
+ +

Starting point

+ +

To get this assessment started, make a local copy of index-finished.html, style.css, and main-finished.js from our last article in a new directory in your local computer.

+ +

Alternatively, you could use a site like JSBin or Glitch to do your assessment. You could paste the HTML, CSS and JavaScript into one of these online editors. If the online editor you are using doesn't have separate JavaScript/CSS panels, feel free to put them inline <script>/<style> elements inside the HTML page.

+ +
+

Note: If you get stuck, then ask us for help — see the {{anch("Assessment or further help")}} section at the bottom of this page.

+
+ +

Hints and tips

+ +

A couple of pointers before you get started.

+ + + +

Project brief

+ +

Our bouncy ball demo is fun, but now we want to make it a little bit more interactive by adding a user-controlled evil circle, which will eat the balls if it catches them. We also want to test your object-building skills by creating a generic Shape() object that our balls and evil circle can inherit from. Finally, we want to add a score counter to track the number of balls left to capture.

+ +

The following screenshot gives you an idea of what the finished program should look like:

+ +

+ + + +

To give you more of an idea, have a look at the finished example (no peeking at the source code!)

+ +

Steps to complete

+ +

The following sections describe what you need to do.

+ +

Creating our new objects

+ +

First of all, change your existing Ball() constructor so that it becomes a Shape() constructor and add a new Ball() constructor:

+ +
    +
  1. The Shape() constructor should define the x, y, velX, and velY properties in the same way as the Ball() constructor did originally, but not the color and size properties.
  2. +
  3. It should also define a new property called exists, which is used to track whether the balls exist in the program (have not been eaten by the evil circle). This should be a boolean (true/false).
  4. +
  5. The Ball() constructor should inherit the x, y, velX, velY, and exists properties from the Shape() constructor.
  6. +
  7. It should also define a color and a size property, like the original Ball() constructor did.
  8. +
  9. Remember to set the Ball() constructor's prototype and constructor appropriately.
  10. +
+ +

The ball draw(), update(), and collisionDetect() method definitions should be able to stay exactly the same as they were before.

+ +

You also need to add a new parameter to the new Ball() ( ... ) constructor call — the exists parameter should be the 5th parameter, and should be given a value of true.

+ +

At this point, try reloading the code — it should work just the same as it did before, with our redesigned objects.

+ +

Defining EvilCircle()

+ +

Now it's time to meet the bad guy — the EvilCircle()! Our game is only going to involve one evil circle, but we are still going to define it using a constructor that inherits from Shape() to give you some practice. You might want to add another circle to the app later on that can be controlled by another player, or have several computer-controlled evil circles. You're probably not going to take over the world with a single evil circle, but it will do for this assessment.

+ +

The EvilCircle() constructor should inherit x, y, velX, velY, and exists from Shape(), but velX and velY should always equal 20.

+ +

You should do this something like Shape.call(this, x, y, 20, 20, exists);

+ +

It should also define its own properties, as follows:

+ + + +

Again, remember to define your inherited properties as parameters in the constructor, and set the prototype and constructor properties correctly.

+ +

Defining EvilCircle()'s methods

+ +

EvilCircle() should have four methods, as described below.

+ +

draw()

+ +

This method has the same purpose as Ball()'s draw() method: It draws the object instance on the canvas. It will work in a very similar way, so you can start by copying the Ball.prototype.draw definition. You should then make the following changes:

+ + + +

checkBounds()

+ +

This method will do the same thing as the first part of Ball()'s update() function — look to see whether the evil circle is going to go off the edge of the screen, and stop it from doing so. Again, you can mostly just copy the Ball.prototype.update definition, but there are a few changes you should make:

+ + + +

setControls()

+ +

This method will add an onkeydown event listener to the window object so that when certain keyboard keys are pressed, we can move the evil circle around. The following code block should be put inside the method definition:

+ +
let _this = this;
+window.onkeydown = function(e) {
+    if (e.key === 'a') {
+      _this.x -= _this.velX;
+    } else if (e.key === 'd') {
+      _this.x += _this.velX;
+    } else if (e.key === 'w') {
+      _this.y -= _this.velY;
+    } else if (e.key === 's') {
+      _this.y += _this.velY;
+    }
+  }
+ +

So when a key is pressed, the event object's keyCode property is consulted to see which key is pressed. If it is one of the four represented by the specified keycodes, then the evil circle will move left/right/up/down.

+ +

For a bonus point, can you tell us why we've had to set let _this = this; in the position it is in? It is something to do with function scope.

+ +

collisionDetect()

+ +

This method will act in a very similar way to Ball()'s collisionDetect() method, so you can use a copy of that as the basis of this new method. But there are a couple of differences:

+ + + +

Bringing the evil circle into the program

+ +

Now we've defined the evil circle, we need to actually make it appear in our scene. To do this, you need to make some changes to the loop() function.

+ + + +

Implementing the score counter

+ +

To implement the score counter, follow the following steps:

+ +
    +
  1. In your HTML file, add a {{HTMLElement("p")}} element just below the {{HTMLElement("h1")}} element containing the text "Ball count: ".
  2. +
  3. In your CSS file, add the following rule at the bottom: +
    p {
    +  position: absolute;
    +  margin: 0;
    +  top: 35px;
    +  right: 5px;
    +  color: #aaa;
    +}
    +
  4. +
  5. In your JavaScript, make the following updates: +
      +
    • Create a variable that stores a reference to the paragraph.
    • +
    • Keep a count of the number of balls on screen in some way.
    • +
    • Increment the count and display the updated number of balls each time a ball is added to the scene.
    • +
    • Decrement the count and display the updated number of balls each time the evil circle eats a ball (causes it not to exist).
    • +
    +
  6. +
+ + + +

Assessment or further help

+ +

If you would like your work assessed, or are stuck and want to ask for help:

+ +
    +
  1. Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch.
  2. +
  3. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: +
      +
    • A descriptive title such as "Assessment wanted for Adding bouncing balls features".
    • +
    • Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment.
    • +
    • A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code.
    • +
    • A link to the actual task or assessment page, so we can find the question you want help with.
    • +
    +
  4. +
+ +

{{PreviousMenuNext("Learn/JavaScript/Objects/Object_building_practice", "", "Learn/JavaScript/Objects")}}

+ +

In this module

+ + diff --git a/files/he/learn/javascript/objects/basics/index.html b/files/he/learn/javascript/objects/basics/index.html new file mode 100644 index 0000000000..25c439e43d --- /dev/null +++ b/files/he/learn/javascript/objects/basics/index.html @@ -0,0 +1,257 @@ +--- +title: JavaScript object basics +slug: Learn/JavaScript/Objects/Basics +translation_of: Learn/JavaScript/Objects/Basics +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects")}}
+ +

במאמר בזה, אנחנו נסתכל על עקרונות הסינטקס הבסיסים של אובייקטים ב-JavaScript, ונבקר בחלק ממאפייניה של השפה שנתקלנו בה בעבר, ונבין כי חלק ממאפיינים אלו הם בעצם אובייקטים.

+ + + + + + + + + + + + +
Prerequisites:Basic computer literacy, a basic understanding of HTML and CSS, familiarity with JavaScript basics (see First steps and Building blocks).
מטרה:הבנת התיאוריה הבסיסית שעומדת מאחורי תכנות מונחה עצמים, כיצד זה מתקשר ל-JavaScript (״רוב הדברים הם אובייקטים״) והבנה כיצד ניתן לעבוד עם אובייקטים ב-JavaScript.
+ +

Object - אובייקטים - עקרונות יסוד

+ +

אובייקט הוא אוסף של מידע או פונקציונליות (בדרך מכיל מספר של מתשנים ופונקציות, אשר נקראים - מאפיינים (properties) ו-מתודות (Methodes) כאשר ה נמצאים בתוך אובייקט). נסתכל על דוגמא על מנת להמחיש את הנושא.

+ +

על מנת להתחיל, הכינו עותק מקומי של oojs.html. קובץ זה מכיל אלמנט של {{HTMLElement("script")}} על מנת שבתוכו נכתוב את הקוד שלנו. אנחנו נשתמש בתצורה הזו על מנת להבין את הסינטקס הבסיסי של אובייקטים. יד עם קובץ זה, פתחו את developer tools JavaScript console.

+ +

כמו בהרבה דברים ב-JavaScript, יצירת אובייקט לרוב מתחילים עם הגדרת ואתחול של משתנה. נסו להכניס את הקוד הבא לתוך קוד ה-JavaScript שבקובץ ולאחר מכן שמרו ורעננו את הדף:

+ +
const person = {};
+ +

כעת פתחו את הקונסולה בדפדפן והזינוו person בתוך הקונסולה, ולאחר מכן לחצו על , Enter/Return. אתם אמורים לקבל תוצאה שנראית כך:

+ +
[object Object]
+Object { }
+{ }
+
+ +

מזל טוב, הרגע יצרתם את האובייקט הראשון שלכם. יחד עם זאת, זהו אובייקט ריק, אז אין יותר מדי מה לעשות איתו. נעדכן את האובייקט שלנו בתוך הקובץ כך שייראה בתצורה הזו:

+ +
const person = {
+  name: ['Bob', 'Smith'],
+  age: 32,
+  gender: 'male',
+  interests: ['music', 'skiing'],
+  bio: function() {
+    alert(this.name[0] + ' ' + this.name[1] + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');
+  },
+  greeting: function() {
+    alert('Hi! I\'m ' + this.name[0] + '.');
+  }
+};
+
+ +

לאחר שמירה ורענון של הדף, נסו להכניס את השורות הבאות לתוך הקונסולה:

+ +
person.name
+person.name[0]
+person.age
+person.interests[1]
+person.bio()
+person.greeting()
+ +

כעת יש לנו מידע ופונקציונליות בתוך האובייקט שלנו, ואנחנו יכולים לגשת אליהם באמצעות סינטקס פשוט:

+ +
+

לתשומת לב: אם אינכם מצליחים לגרום לכך לעבוד, נסו להשוות אל מול הקובץ שלנו oojs-finished.html או ראו את דף האינטרנט ופתחו את הקונסולה בדף זה

+
+ +

אובייקט מורכב ממספר רכיבים, כאשר לכל רכיב יש שם   (name ו- age למעלה), וכן יש לכל רכיב value (e.g. ['Bob', 'Smith'] ו- 32). כל צמד של שם/ערך חייב להיות מופרד באמצעות פסיק , והשם והערך בכל צמד חייבים להיות מופרדים עם :. הסינטקס תמיד ייראה בתבנית הזו:

+ +
const objectName = {
+  member1Name: member1Value,
+  member2Name: member2Value,
+  member3Name: member3Value
+};
+ +

הערך של אובייקט יכול להיות כל דבר - במקרה שלנו, האובייקט person, יש לנו מחרוזת, מספר, שני מערכים, ושתי פונקציות. ארבעת הצמדים הראשונים הם פריטי מידע והם נקראים כ-properties של האובייקט. שני הצמדים האחרונים אלו פונקציות שמאפשרות לאובייקט לעשות משהו עם המידע הזה, והם נקראים ה-methods של האובייקט.

+ +

אובייקט כמו זה נקרא object literal — אנחנו באופן ליטראלי )מפורש) יצרנו את האובייקט והתוכן שלו. זה בניגוד לאובייקטים שנוצרו ממחלקות (classs) שאשר נראה בהמשך.

+ +

זה נפוץ מאוד ליצור אובייקט באמצעות object literal כאשר אנחנו רוצים להעביר סדרה של פריטי מידע קשורים ובמבנה מסויים, לדוגמא, שליחת בקשה לשרת לצורך השמה במאגר המידע. שליחה של אובייקט יחיד היא יעילה יותר מאשר שליחה של כמה פריטי מידע בנפרד, וזה קל יותר לעבוד עם אובייקט מאשר עם מערך, כאשר אנחנו רוצים לזהות כל פריט באמצעות השם שלךו.

+ +

Dot notation שימוש בנקודה-

+ +

למעלה, אנחנו יכולים לגשת למתודות ולפרופ׳ של האובייקט באמצעות dot notation. שם האובייקט - person - משמש כ-namespace - הוא חייב להיות מוכנס ראשון, על מנת לקבל גישה לכל מה שמוכס - encapsulated בתוך האובייקט. לאחר מכן אנחנו רושמים נקודה . ואז את הפריט מידע שאנחנו רוצים לגשת אליו - זה יכול שם של פרופ׳ מסויים, או לקרוא לאחת מהמתודות של האובייקט. לדוגמא:

+ +
person.age
+person.interests[1]
+person.bio()
+ +

Sub-namespaces

+ +

זה אפילו אפשרי ליצור אובייקט כערך מסויים של אובייקט אחר. כך לדוגמא, נסו לשנות את ערך הפרופ׳ name מהקוד הבא:

+ +
name: ['Bob', 'Smith'],
+ +

לקוד זה:

+ +
name : {
+  first: 'Bob',
+  last: 'Smith'
+},
+ +

כאן אנחנו בעצם יצרנו sub-namespace. זה אולי נשמע מורכז, אבל זה לא - על מנת לגשת לפריטים אלו, אנחנו פשוט צריכים להשתמש בעוד נקודה .. נסו להזין את הקוד הבא בקונסולה:

+ +
person.name.first
+person.name.last
+ +

חשוב: לאחר שינוי זה אתם צריכים גם לשנות במתודות את צורת הכתיבה לאור כך ששינינו את הערך ממערך לאובייקט

+ +
name[0]
+name[1]
+ +

לתצורה הבאה:

+ +
name.first
+name.last
+ +

אחרת המתודות לא יעבדו.

+ +

Bracket notation - שימוש בסוגריים מרובעות

+ +

יש דרך נוספת לגשת לפרופ׳ של האובייקט - באמצעות שימוש בסוגריים מרובעות. במקום הקוד הבא:

+ +
person.age
+person.name.first
+ +

אנחנו יכולים להשתמש בקוד זה:

+ +
person['age']
+person['name']['first']
+ +

זה אמנם נראה מאוד דומה לדרך שבה אנחנו ניגשים לאיברים במערך, ובעיקרון זה אותו דבר - אך במקום להשתמש במספר אינדקס על מנת לבחור איבר מסויים, כפי שנאחנו עושים במערך, אנחנו משתמשים בשם המקושר לכל ערך. זה לא פלא שלפעמים אובייקטים נקראים associative arrays — they map strings to values in the same way that arrays map numbers to values.

+ +

הגדרת מפתחות ומתודות לאובייקט -

+ +

עד עכשיו ראינו כיצד לאחזר או לגשת לפריטים באובייקט - אך אנחנו יכולים גם לקבוע או לעדכן את הערכים של אותם פריטים ואף ליצור מפתחות ומתודות חדשים, באמצעות הצהרה על אותו מפתח או מתודה שאנחנו רוצים לעדכן או קבוע - (באמצעות שימוש בנקודה או בסוגריים המרובעות) כך:

+ +
person.age = 45;
+person['name']['last'] = 'Cratchit';
+ +

נסו להזין את השורות למעלה ואז לגשת לערכים ששיניתם באמצעות הקוד על מנת לראות השינוי:

+ +
person.age
+person['name']['last']
+ +

קביעת ערכים במפתחות או מתודות קיימים היא רק אחד מהדברים שניתן לעשות. כפי שאמרנו למעלה, ניתן גם ליצור מפתחות ומתודות חדשים לאותו אובייקט. נסו להזין את הקוד הבא בקונסולה:

+ +
person['eyes'] = 'hazel';
+person.farewell = function() { alert("Bye everybody!"); }
+ +

וכעת בדקו את המפתח והמתודה החדשה כך:

+ +
person['eyes']
+person.farewell()
+ +

היבט מאוד שימושי של שימוש בסוגריים מרובעות הוא שזה לא רק מאפשר לנו לקבוע את הערכים של אותו פריט בצורה דינאמית, אלא גם את השם של אותו פרופ׳ . נניח שאנחנו רוצים שהמשתמשים יוכלו לאחסן ערכים שונים בתוך המידע, באמצעות One useful aspect of bracket notation is that it can be used to set not only member values dynamically, but member names too. Let's say we wanted users to be able to store custom value types in their people data, by typing the member name and value into two text inputs. We could get those values like this:

+ +
let myDataName = nameInput.value;
+let myDataValue = nameValue.value;
+ +

We could then add this new member name and value to the person object like this:

+ +
person[myDataName] = myDataValue;
+ +

To test this, try adding the following lines into your code, just below the closing curly brace of the person object:

+ +
let myDataName = 'height';
+let myDataValue = '1.75m';
+person[myDataName] = myDataValue;
+ +

Now try saving and refreshing, and entering the following into your text input:

+ +
person.height
+ +

הוספת פרופ׳ לאובייקט באמצעות המתודה לעיל אינה אפשרית כאשר אנחנו משתמשים ב-dot notation, כי היא מקבלת רק ערך ליטרלי ולא ערך של משתנה מסויים שמצביע על אותו שם.

+ +

מה זה "this"?

+ +

אולי שמתם לב למשהו קצת מוזר בתוך המתודות שלנו. ראו את הדוגמא הבאה:

+ +
greeting: function() {
+  alert('Hi! I\'m ' + this.name.first + '.');
+}
+ +

אתם בטח שואלים את עצמכם מה זה "this". המילה השומרה this מתייחסת לאובייקט שהקוד נכתב בתוכו - אז במקרה הזה המילה this שווה ל- person. אז מדוע לא לרשום person במקום? כפי שתראו במאמר שלנו בנושאObject-oriented JavaScript מתחילים - כאשר אנחנו יוצרים קונסטרקטורים, המילה this היא מאוד שימושית - היא תבטיח לנו תמיד שהערכים הנכונים מושמים בכל פעם שהמופעים של האובייקט פפפפפ נוצרים - גלומר - אובייקטים שנוצרו - 999999, יהיו בעלי ערכים שונים article, when we start creating constructors and so on, this is very useful — it will always ensure that the correct values are used when a member's context changes (e.g. two different person object instances may have different names, but will want to use their own name when saying their greeting).

+ +

ננסה לפשט ולהסביר באמצעות יצירת שני אובייקטים של person:

+ +
const person1 = {
+  name: 'Chris',
+  greeting: function() {
+    alert('Hi! I\'m ' + this.name + '.');
+  }
+}
+
+const person2 = {
+  name: 'Brian',
+  greeting: function() {
+    alert('Hi! I\'m ' + this.name + '.');
+  }
+}
+ +

במקרה הזה, person1.greeting() יציג "Hi! I'm Chris.";ואילו person2.greeting() יציג "Hi! I'm Brian.", למרות שהקוד של המתודה הוא זהה לחלוטין. כפי שאמרנו למעלה, this שוה בעצם לאובייקט שהקוד נמצא בתוכו - this לא משמעותי ושימושי כאשר אנחנו יוצרים אובייקטים באמצעות אובייקט ליטראלי, אבל הוא מאוד שימושי כאשר אנחנו יוצרים אובייקטים באופן דינאמי (באמצעות קונסטרקטורים לדוגמא). זה יהיה ברור יותר בהמשך הדרך, מבטיחים.

+ +

השתמשנו באובייקטים לאורך כל הזמן הזה

+ +

ככל שאנחנו עוברים על הדוגמאות הללו, אתם בטח חושבים לעצמכם שכבר השתמשנו בעבר בתחביר של סימון נקודה, וזה נכון. בכל פעם שאנחנו השתמשנו בדוגמא אשר משתמשת ב-api מובנה של הדפדפן או באובייקט של javascript, אנחנו בעצם השתמשנו באובייקטים, מכיוון שאותם מאפיינים נבנו באמצעות שימוש במבנה זה למבנה של אובייקט שהסברנו עליו במודול זה, אמנם בצורה קצת יותר מורכבת מהדוגמאות שלנו כאן, אך במבנה דומה.

+ +

כאשר אנחנו משתמשים במתודות של מחרוזות כאלו לדוגמא:

+ +
myString.split(',');
+ +

אנחנו בעצם מתשמשים במתודה שזמינה לנו באמצעות האובייקט הגלובלי String. בכל פעם שאנחנו יוצרים מחרוזת בקוד שלנו, מחרוזת זו באופן אוטומטי נוצרת כמופע/מודל/דוגמא של String, ולכן יש לה מספר מתודות ופרופ׳ אשר זמינות לה.

+ +

כאשר אנחנו ניגשים ל-document object model אמצעות הקוד הבא:

+ +
const myDiv = document.createElement('div');
+const myVideo = document.querySelector('video');
+ +

אנחנו מתשמשים במתודות שזמינות לנו עבור מופע של ה-Document. לכל דף אינטרנט שמועלה, נוצר מופע של Document, אשר נקרא documentוהוא מייצג את כל המבנה, תוכן ומאפיינים נוספים של אותו דף (כמו לדוגמא ה-URL שלו). וזה אומר שיש לו מספר מתודות ומפתחות שזמינים עבור אותו מופע זה.

+ +

אותו הדבר בערך קורה עם הרבה אובייקטים מובנים/api שאנחנו משתשמים בהם — Array, Math, וכך הלאה.

+ +

שימו לב שbuilt in Objects/APIs לא תמיד יוצרים מופעים של אובייקט באופן אוטומטי. לדוגמא, ה- Notifications API — אשר מאפשר לדפדפנים מודרניים להזרים התראות מערת - דורש מאיתנו לייצר מופע אובייקט חדש באמצעות קונסטקטור, עבור כל התראה שנרצה להזרים. נסו להזין את הקוד הבא בקוסולה: :

+ +
const myNotification = new Notification('Hello!');
+ +

אנו נסתכל על קונסרקטורים במאמרים הבאים.

+ +
+

לתשומת לב: זה מאוד שימושי לחשוב על הדרך שבה אובייקטים מתקשרים כ- message passing — כאשר אובייקט אחד צריך אובייקט אחד על מנת לבצע פעולה מסויימת, הוא לרוב ישלח הודעה לאותו אובייקט באמצעו תאחת המתודות שלו ויחכה לתגובה, שהיא בעצם ה- return value.

+
+ +

לסיכום

+ +

סיימנו את המאמר הראשונות שלנו בנושא אובייקטים ב-JavaScript - כעת, אמור להיות לכם בסיס כיצד לעבוד עם אובייקטים ב-JavaScript, כיצד ליצור אובייקטים פשוטים בעצמם. הבנו גם שאובייקטים הם מבנה מאוד שימוש לאחסון של מידע ופונקציונליות הקשורים זה בזה - אם היינו מנסים לשמור את כל המידע והפונקציונליות של האובייקט person כמשתנים ופונקציות נפרדות, זה היה מאתגר וקשה. אבוייקטים מאפשרים לנו לשמור את המידע בצורה בטוחה ונעולה בתוך חבילה משל עצמו.

+ +

במאמר הבא אנחנו נסתכל על תיאוריית object-oriented programming (OOP), וכיצד טכניקות שכאלו יכולות לשמש אותנו ב- JavaScript.

+ +

{{NextMenu("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects")}}

+ +

במודול זה

+ + diff --git a/files/he/learn/javascript/objects/index.html b/files/he/learn/javascript/objects/index.html new file mode 100644 index 0000000000..3b033ee0e8 --- /dev/null +++ b/files/he/learn/javascript/objects/index.html @@ -0,0 +1,54 @@ +--- +title: Introducing JavaScript objects +slug: Learn/JavaScript/Objects +tags: + - Article + - Assessment + - Beginner + - CodingScripting + - Guide + - JavaScript + - Learn + - NeedsTranslation + - Objects + - TopicStub + - Tutorial +translation_of: Learn/JavaScript/Objects +--- +
{{LearnSidebar}}
+ +

ב-JavaScript, רוב הדברים הם אובייקטים, החל מהמאפיינים הבסיסיים של השפה כמו מחרוזות ומערכים, ועד {{Glossary("API", "APIs")}} של הדפדפן שבנויים מעל JavaScript. אנחנו אפילו יכולים ליצור אובייקטים בעצמנו, ו-״להכמיס״ בתוכן פונקציות ומשתנים כך שיתפקדו ככלי להכלת מידע מאוד שימושי. חשוב להבין את הרעיון של JavaScript סביב האובייקט אם אנחנו רוצים להמשיך להתקדם בלמידה שלנו של שפה זו, ומודול זה נועד בדיוק לשם כך. במודול זהנלמד על התיאוריה סביב אובייקט וכן על הסינטקס בפרטים ומשם נמשיך ליצירת אובייקטים בעצמנו

+ +

ידע מוקדם

+ +

לפני שתחלו בלימוד מודול זה, ודאו כי אתם בקיאים ב- {{Glossary("HTML")}} וב- {{Glossary("CSS")}}. אנו ממליצים לכם לעבור על המודולים בנושא הכרות עם HTML ו-הכרות עם CSS לפני שתמשיכו בלימוד JavaScript.

+ +

בנוסף, הנכם מתבקשים לעבור על עקרונות הבסיס של JavaScript לפני שתמשיכו במודול זה. לשם כך, וודאו כי הנכם בקיאי במודול צעדים ראשונים ב-JavaScript ובמודול אבני הבניין של JavaScript לפני שתמשיכו במודול זה.

+ +
+

הערה: אם אתם עובדים על מחשב\טבלט\מכשיר אחר שאין לכם אפשרות ליצור עליו קבצים אישיים, אתם יכולים לנסות את (רוב) דוגמאות הקוד על תוכנות קוד אינטרנטיות כמו JSBin או Thimble.

+
+ +

Guides

+ +
+
אובייקטים - עקרונות יסוד
+
במאמר הראשון אנחנו נסתכל על אובייקטים ב-JavaScript, ועל הסינטקס הבסיסי והחשוב של אובייקט. נבקר שוב כמה מאפשרויות של JavaScript שכבר ראינו לפני כן בקורס, ונבין שהרבה מאותן אפשרויות אלו שנתקלנו בהן בעבר, הן בעצם אובייקטים.
+
תכנות מונחה עצמים ב-JavaScript למתחילים
+
לאחר שסיימנו עם הבסיס, נתמקד במעבר על התיאוריה של תכנות מונחה עצמים (object-oriented programming (OOP)) ב-JavaScript (object-oriented JavaScript (OOJS)) - מאמר זה יספק רקע בסיסי על תכנות מונחה עצמים בכלל, ולאחר מכן נחקור כיצד JavaScript מחקה (מלשון: חיקוי) מחלקות (classes) באמצעות constructor functions ואיך אנחנו יוצרים אובייקט.
+
Object prototypes - טיפוסי אב של אובייקט
+
טיפוסי אב - Prototypes - זה המנגנון שבאמצעותו אובייקטים ב-JavaScript יורשים מאפיינים אחד מהשנים, והם עובדים בצורה אחרת מאשר מנגנוני הורשה הקיימים בשפות לתכנות מונחה עצמים אחרות. במאמר זה אנחנו נחקור את ההבדלים השונים, נסביר כיצד שרשרת אבי הטיפוס (prototype chains) עובדת ונסתכל על איך ה-property שנקרא prototype יכול לשמש על מנת להוסיף מתודות לקונסטרקטורים קיימים.
+
הורשה ב-JavaScript
+
לאחר שסיימנו להסביר על התיאוריה של תכנות מונחה עצמים (object-oriented programming (OOP)) ב-JavaScript, מאמר זה יראה איך ליצור מחלקות בנות (constructors) שיורשות מאפיינים מהמחלקות ״הורים״ With most of the gory details of OOJS now explained, this article shows how to create "child" object classes (constructors) that inherit features from their "parent" classes. In addition, we present some advice on when and where you might use OOJS.
+
Working with JSON data
+
JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax, which is commonly used for representing and transmitting data on web sites (i.e. sending some data from the server to the client, so it can be displayed on a web page). You'll come across it quite often, so in this article we give you all you need to work with JSON using JavaScript, including parsing the JSON so you can access data items within it and writing your own JSON.
+
Object building practice
+
In previous articles we looked at all the essential JavaScript object theory and syntax details, giving you a solid base to start from. In this article we dive into a practical exercise, giving you some more practice in building custom JavaScript objects, which produce something fun and colorful — some colored bouncing balls.
+
+ +

Assessments

+ +
+
Adding features to our bouncing balls demo
+
In this assessment, you are expected to use the bouncing balls demo from the previous article as a starting point, and add some new and interesting features to it.
+
diff --git a/files/he/learn/javascript/objects/inheritance/index.html b/files/he/learn/javascript/objects/inheritance/index.html new file mode 100644 index 0000000000..1d43d06d14 --- /dev/null +++ b/files/he/learn/javascript/objects/inheritance/index.html @@ -0,0 +1,437 @@ +--- +title: Inheritance in JavaScript +slug: Learn/JavaScript/Objects/Inheritance +translation_of: Learn/JavaScript/Objects/Inheritance +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects/JSON", "Learn/JavaScript/Objects")}}
+ +

לאחר שסיימנו עם התיאוריה והפרטים של OOJS, המאמר הזה נועד להראות כיצד ליצור מחלקות אובייקטים ״ילדים״ (constructors) אשר יורשים מההורים שלהם. אנו גם נציג מעין עצות מתי נרצה להשתמש ב-OOJS ונסתכל כיצד ״מחלקות״ מתבצעות בסינטקס המודרני של ECMAScript.

+ + + + + + + + + + + + +
ידע מוקדם: +

אוריינות מחשב בסיסית, הבנה בסיסית ב-HTML ו ב-CSS, היכרות עם יסודות ה-JavaScript (ראה First steps and Building blocks) and OOJS basics (see Introduction to objects).

+
מטרה:להבין כיצד זה אפשרי להחיל הורשה ב- JavaScript
+ +

Prototypal inheritance

+ +

עד עכשיו ראינו קצת הורשה בפעולה - ראינו כיצד prototype chains עובדות וכיצד מתודות ופרופ׳ מורשים בהמשך השרשרת. אבל זה היה בעיקר עם פונקציות מובנות של הדפדפן. כיצד אנחנו יכולים ליצור אובייקט ב-JavaScript אשר יורש מאובייקט אחר?

+ +

דוגמא:

+ +

ראשית, עשו עותק מקומי של הקובץ או ראו אותו כדף אינטרנט. בקוד זה אתם תראו את ה-Person() constructor שהשתמשנו בו לאורך המודול, עם שינוי קל - הגדרנו רק את ה-properties בתוך ה-constructor.

+ +
function Person(first, last, age, gender, interests) {
+  this.name = {
+    first,
+    last
+  };
+  this.age = age;
+  this.gender = gender;
+  this.interests = interests;
+};
+ +

כל המתודות כולן מוגדרות בתוך ה-constructor's prototype. לדוגמא:

+ +
Person.prototype.greeting = function() {
+  alert('Hi! I\'m ' + this.name.first + '.');
+};
+ +
+

לתשומת לבך: בקוד המקור אתם גם תראו מתודות נוספות שמוגדרות, ()bio ו-()farewell. אנחנו נראה בהמשך כיצד מתודות אלו יכולות להיות מורשות ל-constructors אחרים.

+
+ +

נניח ואנחנו רוצים ליצור מחלקה של Teacher, כמו זו שהסברנו בתחילת המודול לגבי תכנות מונחה עצמים, ומחלקה זו יורשת את כל הפרופ׳ והמתודות של Person, אבל גם כוללת:

+ +
    +
  1. ה- property החדש בשם subject — אשר יכיל את נושאי הלימוד שהמורה מלמד.
  2. +
  3. מתודה ()greeting מעודכנת, אשר תהיה יותר רשמית מהמתודה ()greeting הרגילה.
  4. +
+ +

הגדרה של ה-constructor function בשם ()Teacher

+ +

הדבר הראשון שאנחנו צריכים לעשות הוא להגדיר את ה-constructor בשם ()Teacher - הוסיפו את הקוד הבא מתחת לקוד הנוכחי:

+ +
function Teacher(first, last, age, gender, interests, subject) {
+  Person.call(this, first, last, age, gender, interests);
+
+  this.subject = subject;
+}
+ +

זה נראה מאוד דומה ל-constructor בשם Person, אבל משהו פה שונה, משהו שלא ראינו עד כה - פונקציה בשם ()call.

+ +

פונקציה זו היא בעיקרון מאפשרת לנו לקרוא לפונקציה שהוגדרה במקום אחר, אבל לקרוא לה בהקשר הנוכחי.

+ +

הפרמטר הראשון שהפונקציה הזו מקבלת מכיל את הערך של this שאנחנו נרצה להשתמש בו כאשר אנחנו מריצים את הפונקציה, והפרמטרים האחרים אלו פרמטרים שאמורים להיות מועברים לפונקציה עצמה כאשר היא מופעלת.

+ +

אנחנו רוצים שה-Teacher() constructor יקבל את אותם פרמטרים כמו שה-Person() constructor שהוא יורש ממנו מקבל, ולכן אנחנו מציינים אותם כפרמטרים בתוך ההפעלה של ה-()call.

+ +

השורה האחרונה בתוך ה-constructor פשוט מגדירה property בשם subject אשר ייחודי למורים, שאנשים רגילים מ-()Person לא מקבלים.

+ +

יכלנו גם לרשום זאת כך, ללא שימוש ב-()call:

+ +
function Teacher(first, last, age, gender, interests, subject) {
+  this.name = {
+    first,
+    last
+  };
+  this.age = age;
+  this.gender = gender;
+  this.interests = interests;
+  this.subject = subject;
+}
+ +

אבל בקוד למעלה זו הגדרה מחדש של ה-properties כחדשים, לא כאלו שיורשים מ- ()Person, אז זה סותר את מה שאנחנו מנסים לעשות - זה לא מוריש אלא זה יוצר חדשים. מה גם שזה לוקח יותר שורות קוד.

+ +

ירושה מ-constructor שלא מקבל פרמטרים

+ +

שימו לב שאם ה-constructor שאנחנו יורשים ממנו לא מקבל את הערכים של ה-property שלו מקבלים מפרמטרים, אז אנחנו לא צריכים לציין אותם כפרמטרים בתוך ה-()call. לדומא, אם היה לנו משהו פשוט כמו זה: :

+ +
function Brick() {
+  this.width = 10;
+  this.height = 20;
+}
+ +

אנחנו יכולים לרשת את ה-properties של ה-width ואת ה-height, באמצעות שימוש בקוד הרשום מטה:

+ +
function BlueGlassBrick() {
+  Brick.call(this);
+
+  this.opacity = 0.5;
+  this.color = 'blue';
+}
+ +

שימו לב שאנחנו רק צריכים לציין את ה-this בתוך ה-()call, ללא פרמטרים נוספים, שכן אנחנו לא יכולים יורשים שום דבר מ-()Brick שהוא קיבל דרך פרמטרים.

+ +

קביעת ה-prototype וה-constructor של ()Teacher

+ +

עד עכשיו הכל עובד תקין, אך יש לנו בעיה. הגדרנו אמנם constructor חדש, ויש לו את ה-property בשם prototype, אשר כברירת מחדל מכיל רק הפנייה ל-constructor function עצמה.

+ +

הוא לא מכיל שום מתודות של ה-property בשם prototype של ה-Person constructor. על מנת לראות זאת, הכניסו (Object.getOwnPropertyNames(Teacher.prototype לתוך הקונסולה.

+ +

לאחר מכן הכניסו זאת שוב, והחליפו את המילה Teacher במילה Person. ה-constructor החדש לא יורש את אותן מתודות. על מנת לראות זאת, השוו את הפלט של Person.prototype.greeting והפלט של Teacher.prototype.greeting. אנחנו צריכים לגרום ל-()Teacher לירוש מתודות שמוגדרות ב-prototype של ()Person. איך עושים זאת?

+ +
    +
  1. הוסיפו את הקוד הבא מתחת לקוד שהוספתם לפני כן: +
    Teacher.prototype = Object.create(Person.prototype);
    + כאן ()create מגיע שוב לעזרה. במקרה הזה, אנחנו משתמשים בו על מנת ליצור אובייקט חדש שיהיה הערך של Teacher.prototype. האובייקט החדש הוא בעל Person.prototype כאובייקט ה-prototype שלו, ולכן, הוא יירש ממנו אם וכאשר יצטרך, את כל המתודות שזמינות ב-Person.prototype.
  2. +
  3. אנחנו צריכים לעשות משהו נוסף לפני שנמשיך הלאה. לאחר שהוספנו את השורה הקודמת, ה-property בשם constructor שווה כעת ל- ()Person, מכיוון שאנחנו הרגע הגדרנו את Teacher.prototype אליו. נסו לשמור את הקוד ולהעלות את הדף בדפדפן וראו זאת על ידי הקלדת Teacher.prototype.constructor בקונסולה.
  4. +
  5. זה יכול להיות בעיה, ולכן אנחנו צריכים לתקן זאת. ניתן לעשות זאת באמצעות הקלדת הקוד הבא מתחת לקוד הנוכחי שלנו.: +
    Object.defineProperty(Teacher.prototype, 'constructor', {
    +    value: Teacher,
    +    enumerable: false, // so that it does not appear in 'for in' loop
    +    writable: true });
    +
  6. +
  7. כעת, אם תשמרו ותרעננו את הדף, הקלדת Teacher.prototype.constructor לקונסולה אמורה להחזיר לכם ()Teacher, כפי שרצינו, ובנוסף אנחנו יורשים מ-()Person.
  8. +
+ +

הענקה ל- Teacher() פונקציית/מתודת greeting() חדשה

+ +

אנו רוצים להגדיר פונקציית ()greeting חדשה בתוך ה-Teacher() constructor שלנו.

+ +

הדרך הפשוטה ביותר לעשות זאת היא להגדיר זאת בתוך ה-prototype של ()Teacher - הוסיפו את הקוד הבא מתחת לקוד הנוכחי:

+ +
Teacher.prototype.greeting = function() {
+  var prefix;
+
+  if (this.gender === 'male' || this.gender === 'Male' || this.gender === 'm' || this.gender === 'M') {
+    prefix = 'Mr.';
+  } else if (this.gender === 'female' || this.gender === 'Female' || this.gender === 'f' || this.gender === 'F') {
+    prefix = 'Mrs.';
+  } else {
+    prefix = 'Mx.';
+  }
+
+  alert('Hello. My name is ' + prefix + ' ' + this.name.last + ', and I teach ' + this.subject + '.');
+};
+ +

מתודה זו מקפיצה את הברכה של המורה, ומשתמשת במילים הנכונות בהתאם למין המורה באמצעות משפטי תנאי שהוגדרו.

+ +

נסו את הדוגמא הבאה:

+ +

כעת שהכנסו את כל הקוד, נסו ליצור אובייקטים חדשים מ-()Teacher באמצעות הכנסת הקוד הבא מתחת לקוד הנוכחי:

+ +
var teacher1 = new Teacher('Dave', 'Griffiths', 31, 'male', ['football', 'cookery'], 'mathematics');
+ +

כעת, שמרו את הדף ורעננו ונסו לגשת לפרופ׳ והמתודות של האובייקט teacher1 החדש שלנו. לדוגמא:

+ +
teacher1.name.first;
+teacher1.interests[0];
+teacher1.bio();
+teacher1.subject;
+teacher1.greeting();
+teacher1.farewell();
+ +

הכל אמור לעבוד כשורה. השורות 1,2,3 ו-6 משתמשות במתודות/פרופ׳ שנורשו מה-Person() constructor שלנו. השורה 4 משתמשת בפרופ׳ שזמין רק באמצעות ה-Teacher() constructor שלנו. שורה 5 הייתה יכולה להיות מורשת מ-()Person, אבל מכיוון של-()Teacher יש את אותה מתודה, אז היא ניגשת למתודה שנמצאת ב-()Teacher.

+ +
+

לתשומת לב: אם נתקלתם בבעיות, נסו להשוות את הקוד שלכם ל קוד הסופי או ראו אותו כ דף אינטרנט.

+
+ +

הטכניקות שראינו עד כה, אינן היחידות ליצירת מחלקות ירושה ב-JavaScript, אבל הן עובדות בסדר, הן נותנות לכם הבנה כיצד להחיל ירושה ב-JavaScript.

+ +

אולי תהיו מעוניינים לבדוק חלק מהאפשרויות החדשות ש-{{glossary("ECMAScript")}} מאפשרת לנו, בצורה ״נקייה״ יותר, באמצעות Classes. אנו נגע בדרך זו בהמשך. שימו לב כי דרך חדשה זו לא תומכת בכל הדפדפנים. כל יתר הדרכים שראינו תומכות בדפדנים ישנים גם כמו IE9 ומוקדם יותר ויש דרכים גם לאפשר תמיכה לדפדפנים ישנים יותר.

+ +

דרך מקובלת היא להשתמש בספריית JavaScript - לפופולריות שביניהן יש סט של פונקציונליות שזמין עבור ביצוע הורשה בצורה פשוטה ומהירה. אחת מהן היא CoffeeScript אשר מאפשרת class ,extends לדוגמא.

+ +

המשך תרגול

+ +

במאמר שלנו בנושא OOP theory section, כללנו גם מחלקת Student באופן עקרוני, אשר יורשת תכונות מ-Person וגם יש לה מתודת ()greeting שונה מזו של Person ומשל Teacher. נסתכל כיצד ה-greeting של התלמידים אמורה להיות וננסה לבנות constructor בשם ()Student משלנו, אשר יורש את כל התכונות מ-()Person ומחיל מתודת ()greeting שונה.

+ +
+

שימו לב: אם אתם נתקלים בבעיות, ראו את הגרסה הסופית או כדף אינטרנט .

+
+ +

סיכום בנושא תכונות האובייקט

+ +

על מנת לסכם, יש לנו בעיקרון שלוש סוגים של property/method לדאוג להם:

+ +
    +
  1. אלו המוגדרים בתוך ה-constructor function וניתנים לאובייקטים שנוצרים באמצעות ה- this. אלו בעיקרון מאוד קלים לאיתור - בתוך הקוד שלנו, אלו התכונות שמוגדרות בתוך ה-constructor באמצעות this.x = x, והם זמינים רק עבור האובייקטים שנוצרים (בדרך כלל נוצרים באמצעות ה-constructor ושימוש במילה השמורה new, לדוגמא: ()var myInstance = new myConstructor.
  2. +
  3. אלו המוגדרים ישרות על ה-constructor עצמם, ואלו זמינות רק על ה-constructor. הם לרוב יהיו זמינים רק אובייקטים מובנים של הדפדפן, ואנחנו יכולים לזהות שהם קשורים באופן ישירות ל-constructor ולא למופע אובייקט. לדוגמא ()Object.keys.
  4. +
  5. ואלו המוגדרים על הפרופ׳ בשם prototype של ה-constructor, אשר נורשים על ידי כל מופעי האובייקט שנוצרים או אובייקטים שיורשים מהם. זה כולל כל תכונה שמוגדרת ב-property בשם prototype של ה-Constructor. לדוגמא: ()myConstructor.prototype.x.
  6. +
+ +

אם אתם לא בטוחים מה זה מה, אל תדאגו, אתם תכירו אותם יותר לעומק במהלך הדרך והמשך הקריירה שלכם ככל שתתמודדו איתם.

+ +

ECMAScript 2015 Classes

+ +

ECMAScript 2015 הציגה מעין סינטקס חדש בשם class syntax ל- JavaScript כדרך חדשה לרשום מחלקות לשימוש חוזר, באמצעות סינטקס פשוט ונקי יותר, אשר דומה יותר ל-classes ב-C++ או ב-Java. בחלק הזה של המאמר אנחנו נמיר את הדוגמאות מלמעלה מ-prototypal inheritance ל-classes, על מנת להראות לכם איך לעשות שימוש-classes.

+ +
+

לתשומת לב: דרך חדשה זו של כתיבת classes נתמכת בכל הדפדפנים המודרניים, אבל זה עדיין חשוב להבין את ה-prototypal inheritance במקרה ותיתקלו בפרוייקט שדורש תמיכה בדפדפן שאינו תומך בסינטקס של classes - הידוע מבין כולם הוא Internet Explorer.

+
+ +

נסתכל על הדוגמא שלנו של Person כתובה בצורת classes:

+ +
class Person {
+  constructor(first, last, age, gender, interests) {
+    this.name = {
+      first,
+      last
+    };
+    this.age = age;
+    this.gender = gender;
+    this.interests = interests;
+  }
+
+  greeting() {
+    console.log(`Hi! I'm ${this.name.first}`);
+  };
+
+  farewell() {
+    console.log(`${this.name.first} has left the building. Bye for now!`);
+  };
+}
+
+ +

ההצהרה באמצעות המילה השמורה class מצהירה בעצם בשאנחנו רוצים ליצור class חדשה. בתוך הבלוק הזה שבין {}, אנחנו מגדירים את התכונות של אותה מחלקה:

+ + + +

כעת אנחנו יכולים ליצור מופעי אובייקט חדשים באמצעות שימוש באופרטור new operator, באותה הדרך שעשינו בעבר:

+ +
let han = new Person('Han', 'Solo', 25, 'male', ['Smuggling']);
+han.greeting();
+// Hi! I'm Han
+
+let leia = new Person('Leia', 'Organa', 19, 'female', ['Government']);
+leia.farewell();
+// Leia has left the building. Bye for now
+
+ +
+

לתשומת לב: מאחורי הקלעים, ה-classes שלנו מומרים ל-prototypal Inheritance models - זהו רק syntactic sugar - שזה אומר דרך אחרת מבחינת סינטקס לעשות דבר זהה, אך לא משהו אחר. יחד עם זאת, אין ספק שזו דרך פשוטה יותר להעניק הורשה.

+
+ +

הורשה עם class syntax

+ +

למעלה יצרנו class על מנת לתאר person. יש לנו סט של תכונות שזהות לכל האנשים. בחלק זה אנחנו ניצור את ה-class המיוחד של Teacher, ונגרום לו לירוש מ-Person באמצעות שימוש בסינטקס class החדש. זה נקרא יצירת subclass או ביצוע subclassing.

+ +

על מנת ליצור subclass אנחנו יכולים להשתמש במילה השמורה extends על מנת להגיד ל-JavaScript איזו class אנחנו מתבססים עליה ביצירת ה-class החדשה:

+ +
class Teacher extends Person {
+  constructor(subject, grade) {
+    this.subject = subject;
+    this.grade = grade;
+  }
+}
+ +

אך יש קאצ׳ קטן:

+ +

שלא כמו ה-Constructor function, שבהן האופרטור new operator היה עושה את האתחול של המילה this לאובייקט חדש, פה זה לא קורה בצורה אוטומטית בעבור המחלקה שמוגדרת באמצעות המילה extends, כלומר עבור ה-sub-classes.

+ +

ולכן הרצה שלהקוד למעלה יציג לנו שגיאה:

+ +
Uncaught ReferenceError: Must call super constructor in derived class before
+accessing 'this' or returning from derived constructor
+ +

למחלקות משנה, sub-classes, ההגדרה של this בעבור אובייקט חדש, תהיה תמיד תלויה ב-parent class constructor, כלומר ב-constructor function של ה-class שממנה אנחנו מתרחבים (extending).

+ +

כאן, אנחנו מרחיבים את המחלקה Person- המחלקת משנה בשם -Teacher היא בעצם extension - הרחבה - של המחלקה Person. אז עבור Teacher האתחול של this מתבצע על ידי ה-constructor Person.

+ +

על מנת לקרוא ל-constructor ה-parent, אנחנו צריכים להשתמשש באופרטור ()super , כך:

+ +
class Teacher extends Person {
+  constructor(subject, grade) {
+    super();              // Now `this` is initialized by calling the parent constructor.
+    this.subject = subject;
+    this.grade = grade;
+  }
+}
+ +

אין שום סיבה שתהיה לנו sub-class אם היא לא יורשת מאפיינים מה-parent class.
+ זה רעיון טוב אז שהאופרטור ()super  גם מקבל ארגומנטים בעבור ה- parent constructor.

+ +

כאשר אנחנו מסתכלים על ה- Person constructor,  אנחנו יכולים לראות שיש לו את הבלוק קוד הבא בתוך ה-constructor שלו:

+ +
 constructor(first, last, age, gender, interests) {
+   this.name = {
+     first,
+     last
+   };
+   this.age = age;
+   this.gender = gender;
+   this.interests = interests;
+} 
+ +

מאחר והאופרטור ()super הוא בעצם ה-parent class constructor, העברה של הארגומנטים הרלוונטיים של המחלקת אם, גם תאתחל את הפרופ׳ במחלקת משנה שלנו, ותירש אותם: 

+ +
class Teacher extends Person {
+  constructor(first, last, age, gender, interests, subject, grade) {
+    super(first, last, age, gender, interests);
+
+    // subject and grade are specific to Teacher
+    this.subject = subject;
+    this.grade = grade;
+  }
+}
+
+ +

כעת, כשיוצרים מופעי אובייקט של Teacher, אנחנו יכולים לקרוא למתודות ופרופ׳ שהוגדרו גם ב-Teacher וגם ב-Person:

+ +
let snape = new Teacher('Severus', 'Snape', 58, 'male', ['Potions'], 'Dark arts', 5);
+snape.greeting(); // Hi! I'm Severus.
+snape.farewell(); // Severus has left the building. Bye for now.
+snape.age // 58
+snape.subject; // Dark arts
+
+ +
+

לתשומת לב: אתם יכולים למצוא את הדוגמא ב-GitHub ב- es2015-class-inheritance.html  או כ-דף אינטרנט.

+
+ +

Getters ו- Setters

+ +

יהיו פעמים שאנחנו נרצה לשנות את הערכים של מאפיין בתוך השאנחנו יוצרים או שאנחנו לא נדע מהו הערך הסופי שאותו מאפיין יקבל. אם נסתכל על הדוגמא שלנו Teacher, יכול להיות מצב שאנחנו לא נדע מה הנושא שהמורה מלמד לפני שאנחנו יוצרים אותו או שהנושא יכול להשתנות במהלך התקופה.

+ +

במקרים כאלו אנחנו נוכל להשתמש ב-getters ו-setters.

+ +

נשפר את Teacher class עם  getters ו-setters. המחלקה מתחילה בדיוק כמו שראינו אותה בדוגמא האחרונה.

+ +

 getters ו-setters עובדים בזוגות. getter מחזיר את הערך הנוכחי של משתנה וה-setter הבן זוג שלו משנה את הערך של המשתנה למה שה-setter יגדיר. 

+ +

המחלקה Teacher החדשה תיראה כך:

+ +
class Teacher extends Person {
+  constructor(first, last, age, gender, interests, subject, grade) {
+    super(first, last, age, gender, interests);
+    // subject and grade are specific to Teacher
+    this._subject = subject;
+    this.grade = grade;
+  }
+
+  get subject() {
+    return this._subject;
+  }
+
+  set subject(newSubject) {
+    this._subject = newSubject;
+  }
+}
+
+ +

במחלקה למעלה יש לנו getter ו-setter בעבור הפרופ׳ subject. אנחנו משתמשים בסימן _ על מנת ליצור ערך נפרד שבו נאחסכן את השם של הפרופ׳. אם לא נעשה זאת בצורה הזה, אנחנו נקבל שגיאות בכל פעם שנקרא ל-get או ל-set. בנקודה זו: 

+ + + +

הדוגמא למטה מראה את השימוש באפשרויות האלו: 

+ +
// Check the default value
+console.log(snape.subject) // Returns "Dark arts"
+
+// Change the value
+snape.subject="Balloon animals" // Sets _subject to "Balloon animals"
+
+// Check it again and see if it matches the new value
+console.log(snape.subject) // Returns "Balloon animals"
+
+ +
+

לתשומת לב : תוכלו למצוא את es2015-getters-setters.html ב-GitHub, או כדף אינטרנט.

+
+ +

מתי אנחנו נשתמש בהורשה ב-JavaScript?

+ +

רוב הסיכויים שלאחר קריאת המאמר הזה, אתם בטח חושבים לעצמכם ״טוב, זה מסובך מאוד״. אתם צודקים. הורשה ואבי טיפוס הינם חלק מההיבטים המורכבים ביותר של JavaScript, אבל הרבה מעוצמתה של השפה והגמישות שלה מגיע מתוך המבנה של האובייקטים והירושה שלהם, וזה שווה להכיר ולהבין כיצד התהליכים הללו מתרחשים. 

+ +

בדרך מסויימת, אנחנו משתמשים בהורשה כל הזמן. בכל פעם שאנחנו משתמשים במאפיינים שונים של Web API או בפרופ׳/מתודות שהוגדרו באובייקט מובנה של הדפדפן (built-in browser object) על מחרוזות, מערכים וכד׳ אנחנו באופן עקיף משתמשים בירושה. 

+ +

במונחים של שימוש בירושה בקוד שלנו, אנחנו ככל הנראה לא נשתמש בזה באופן תדיר, במיוחד בהתחלה ובפרוייקטים קטנים. זה בזבוז זמן להשתמש באובייקטים וירושה רק לשם השימוש בהם אם אנחנו לא צריכים. אבל ככל שכמות הקוד גדלה, אנחנו ככל הנראה נזהה את הצורך להתחיל להשתמש בכך. םא אנחנו מוצאים את עצמנו מתחילים ליצור מספר אובייקטים שיש להם מאפיינים זהים, אז יצירת אובייקט גנרי אחד אשר יכיל את כל הפונקציונליות המשותפת של אותם אובייקטים ויוריש להם את אותה פונקציונליות תהיה דרך מאוד שימושית ונוחה.

+ +
+

לתשומת לב: לאור הדרך שבה JavaScript עובדת עם שרשרת אבי הטיפוס (prototype chain) וכד׳ - השיתוף של פונקציונליות בין אובייקטים נקרא לרוב delegation - ״האצלה״. אובייקטים מיוחדים ״מאצילים״ פונקציונליות לאובייקטים שנוצרים.  

+
+ +

כאשר אנחנו משתמשים בהורשה, ההמלצה היא שלא יהיו יותר מדי רמות של הורשה, ושתמיד נעקוב איפה אנחנו מגדירים את המתודות והפרופ׳. זה אפשרי להתחיל לכתוב קוד שבאופן זמני משנה את ה-prototypes של האובייקטים המובנים של הדפדפן (built-in browser objects), אבל אין לעשות זאת אלא אם כן יש לנו סיבה מאוד טובה. יותר מדי הורשה יכולה להוביל לבלבול אינסופי ולשגיאות בקוד. 

+ +

באופן אולטמטיבי, אובייקטים הם פשוט תבנית אחרת של שימוש חוזר בקוד, כמו פונקציות ולולאות, עם הכללים והיתרונות שלהם. אם אתם מוצאים את עצמכם יוצרים משתנים ופונקציות הקשורים אחד לשני ואתם רוצים לעקוב ולארוז אותם יחד בצורה מסודרת, אובייקט הוא רעיון טוב. אובייקטים גם שימושיים מאוד כשאנחנו רוצים להעביר ריכוז של מידע ממקום אחד למקום שני. את שני הדברים הללו ניתן להשיג ללא שימוש ב-constructors או ב-inheritance. אם אנחנו צריכים רק מופע אחד של אובייקט, כנראה יהיה עדיף פשוט להשתמש ב-inheritance ואין צורך בירושה.

+ +

אלטרנטיבות להרחבה של שרשרת ההורשה 

+ +

ב-JavaScript, יש מספר דרכים שונות להרחבה של ה-prototype של אובייקט חוץ מאלו שראינו במאמר זה. להרחבה בנושא, ראו את הדף שלנו בנושא Inheritance and the prototype chain.

+ +

לסיכום

+ +

מאמר זה נועד לסקור את יתרת הנושא של OOJS וסינטקס נוסף שאנחנו חושבים שאתם צריכים לדעת. בנקודה זו אתם אמורים להבין את ההיבטים של אובייקטים ב-JavaScript ואת הבסיס של תכנות מונחה עצמים (OOP), אביט טיפוס, שרשרת אבי-טיפוס, הורשה באמצעות אבי-טיפוס, כיצד ליצור מחלקות (classes), מופעי אובייקטים, הוספת מאפיינים למחלקות, יצירת מחלקות משנה שיורשות ממחלקות אחרות ועוד. 

+ +

במאמר הבא אנחנו נגע כיצד לעבוד עם (JavaScript Object Notation (JSON, פורמט מקובל להעברת מידע.

+ +

ראו גם

+ + + +

{{PreviousMenuNext("Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects/JSON", "Learn/JavaScript/Objects")}}

+ +

במודול זה

+ + diff --git a/files/he/learn/javascript/objects/json/index.html b/files/he/learn/javascript/objects/json/index.html new file mode 100644 index 0000000000..5f61b5aa22 --- /dev/null +++ b/files/he/learn/javascript/objects/json/index.html @@ -0,0 +1,346 @@ +--- +title: Working with JSON +slug: Learn/JavaScript/Objects/JSON +translation_of: Learn/JavaScript/Objects/JSON +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Objects/Inheritance", "Learn/JavaScript/Objects/Object_building_practice", "Learn/JavaScript/Objects")}}
+ +

JavaScript Object Notation (JSON) הוא סטדנרט לפורמט מבוסס-טקסט, המבוסס על הסינטקס של אובייקט ב-ה. הוא לרוב משמש בעבור העברת מידע ביישומי רשת (כלומר העברת מידע משרת לקוח, כך שהמידע יוכל להיות מוצג על גבי דף אינטרנט, או ההפך). אנחנו ניתקל בו לעיתים קרובות מאוד ומאמר זה נועד להעניק לכם כל מה שצריך לדעת על עבודה עם JSON כשאנחנו משתמשים ב-JavaScript, כולל עיבוד שלו כך שאנחנו נוכל לגשת למידע המאוחסן בו וכן ליצור JSON.

+ + + + + + + + + + + + +
ידע מוקדם:Basic computer literacy, a basic understanding of HTML and CSS, familiarity with JavaScript basics (see First steps and Building blocks) and OOJS basics (see Introduction to objects).
מטרה:להבין כיצד לעבוד עם מידע המאוחסן בתוך JSON וכיצד ליצור אובייקטי JSON בעצמנו.
+ +

מה זה JSON?

+ +

{{glossary("JSON")}} הוא פורמט מידע מבוסס-טקסט אשר דומה לסינטקס של אובייקט ב-JavaScript. פורמט זה הוצג על ידי Douglas Crockford. למרות שהוא מאוד דומה ומזכיר סינטקס של object literal ב-JavaScript, ניתן להשתמש בו באופן עצמאי ולא רק ב-JavaScript, וסביבות פיתוח אחרות מכילות אפשרויות לקרוא או לעבד וכן ליצור JSON. 

+ +

JSON מתקיים כמחרוזת - שימושי מאוד כשאנחנו רוצים להעביר מידע ברשת. הוא צריך להיות מומר לאובייקט JavaScript כאשר אנחנו רוצים לגשת לאותו מידע שמאוחסן בתוך ה-JSON. זה לא מורכב או מסובך - JavaScript מעניקה לנו את האובייקט JSON הגלובלי שיש לו מתודות שזמינות עבורו בעבור המרה בין JSON למחרוזת.

+ +
+

לתשומת לב: המרה של מחרוזת לאובייקט נקראת parsing ואילו המרה של אובייקט למחרזות כך שהוא יוכל להיות מועבר ברשת, נקראת stringification.

+
+ +

אובייקט JSON יכול להיות מאוחסן בתוך קובץ נפרד משלו, שהוא בעצם קובץ טקסט עם סיימות של .json ו-{{glossary("MIME type")}} של application/json.

+ +

המבנה של JSON

+ +

כפי שציינו למעלה, JSON הוא מחרוזת, שהמבנה שלה מזכיר מאוד object literal ב-JavaScript. אנחנו יכולים לכלול את אותם סוגי מידע בסיסיים בתוך JSON כפי אנחנו יכולים לכלול אותם בתוך אובייקט של JavaScript - מחרוזות, מספרים, מערכים, בוליאנים ואובייקטים אחרים. זה מאפשר לנו ליצור היררכיית מידע כמו זו לדוגמא:

+ +
{
+  "squadName": "Super hero squad",
+  "homeTown": "Metro City",
+  "formed": 2016,
+  "secretBase": "Super tower",
+  "active": true,
+  "members": [
+    {
+      "name": "Molecule Man",
+      "age": 29,
+      "secretIdentity": "Dan Jukes",
+      "powers": [
+        "Radiation resistance",
+        "Turning tiny",
+        "Radiation blast"
+      ]
+    },
+    {
+      "name": "Madame Uppercut",
+      "age": 39,
+      "secretIdentity": "Jane Wilson",
+      "powers": [
+        "Million tonne punch",
+        "Damage resistance",
+        "Superhuman reflexes"
+      ]
+    },
+    {
+      "name": "Eternal Flame",
+      "age": 1000000,
+      "secretIdentity": "Unknown",
+      "powers": [
+        "Immortality",
+        "Heat Immunity",
+        "Inferno",
+        "Teleportation",
+        "Interdimensional travel"
+      ]
+    }
+  ]
+}
+ +

אם אנחנו נטען את האובייקט הזה לתוך תוכנית JavaScript ונמיר אותו (parse) בתוך משתנה בשם superHeroes לדוגמא, אנחנו אז נוכל לגשת לאותו מידע המאוחסן בו באמצעות שימוש ב-00000 שאנחנו מכירים מהמאמר בנושא אובייקטים - עקרונות יסוד. לדוגמא: 

+ +
superHeroes.homeTown
+superHeroes['active']
+ +

על מנת לגשת למידע בהמשך ההיררכיה, אנחנו פשוט נצטרך ״לקשור״ את שם הפרופ׳ המבוקש והאינדקס הרלוונטי במערך ביחד. לדוגמא, על מנת לגשת ל-9999 השלישי של ה-0000 השני ברשימת ה-9999, נוכל לרשום קוד כזה:

+ +
superHeroes['members'][1]['powers'][2]
+ +
    +
  1. ראשית יש לנו את שם המשתנה  — superHeroes.
  2. +
  3. בתוך המשתנה אנחנו רוצים לגשת לפרופ׳ members, אז אנחנו משתמשים ב- ["members"]
  4. +
  5. members מכיל מערך של אובייקטים. אנחנו רוצים לגשת לאובייקט השני בתוך המערך אז אנחנו נשתמש באינדקס [1]
  6. +
  7. בתוך האובייקט, אנחנו רוצים לגשת לפרופ׳ powers, אז אנחנו נשתמש ב-["powers"]
  8. +
  9. ובתוך הפרופ׳ powers, אנחנו נרצה את הערך השלישי, אז אנחנו נשתמש ב-[2]
  10. +
+ +
+

לתשומת לב: יצרנו את ה-JSON שבדוגמא למעלה בקובץ JSONTest.html וניתן לראותו גם ב-קוד המקור

+ +

מנסו להעלות את הקובץ ולגשת למידע בתוך המשתנה באמצעות הקונסולה בדפדפן. 

+
+ +

מערכים כ-JSON

+ +

למעלה ציינו שטקסט ב-JSON דומה בעקרון לאובייקט ב-JavaScript, וזה דיי נכון. הסיבה שאנחנו אומרים ״דומה״ ולא ״זהה״, מכיוון שמערך ב-JavaScript הוא בעצם JSON תקין:

+ +
[
+  {
+    "name": "Molecule Man",
+    "age": 29,
+    "secretIdentity": "Dan Jukes",
+    "powers": [
+      "Radiation resistance",
+      "Turning tiny",
+      "Radiation blast"
+    ]
+  },
+  {
+    "name": "Madame Uppercut",
+    "age": 39,
+    "secretIdentity": "Jane Wilson",
+    "powers": [
+      "Million tonne punch",
+      "Damage resistance",
+      "Superhuman reflexes"
+    ]
+  }
+]
+ +

הטקסט למעלה הוא JSON תקין לחלוטין. אנחנו פשוט נצטרך לגשת לאיברים במערך (בגרסה המעובדת שלו), באמצעות אינדקס של מערך/

+ +

הערות נוספות

+ + + +

למידה עצמאית: עבודה עם JSON

+ +

כעת נלמד באמצעות דוגמא כיצד ניתן לעשות שימוש במידע JSON באתר אינטרנט.

+ +

התחלה

+ +

על מנת להתחיל, עשו עותקים מקודמיים של heroes.html ושל style.css . הקובץ האחרון מכיל CSS פשוט לעיצוב הדף שלנו והראשון מכיל גוף HTML פשוט:

+ +
<header>
+</header>
+
+<section>
+</section>
+ +

בנוסף, הקובץ הראשון מכיל אלמנט {{HTMLElement("script")}} פשוט שיכיל את קוד ה-JavaScript שנכתוב בתרגיל זה. כעת, קובץ זה מכיל שתי שורות, אשר מכילות הפניה לאלמנט {{HTMLElement("header")}} ולאלמנט {{HTMLElement("section")}} ומאחסן הפניות אלו בתוך משתנים:

+ +
var header = document.querySelector('header');
+var section = document.querySelector('section');
+ +

מידע ה-JSON זמין ב-GitHub בכתובת: https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json.

+ +

בתרגיל אנחנו נעלה את המידע לתוך הדף שלנו, באמצעות שימוש במניפולציות על ה-DOM, כך שהדף שלנו ייראה כך:

+ +

+ +

קבלת ה-JSON

+ +

על מנת להשיג את ה-JSON, אנחנו נשתמש ב-API שנקרא {{domxref("XMLHttpRequest")}} (לרוב נקרא XHR). זהו אובייקט JavaScript שימושי מאוד, אשר מאפשר לנו לבצע בקשות רשת על מנת לקבל משאבים מהשרת באמצעות JavaScript (כמו תמונות, טקסט, JSON, ואפילו קוד HTML), כלומר, אנחנו יכולים לעדכן חלקים מתוך התוכן שלנו, מבלי לטעון מחדש את הדף כולו. אפשרות זו איפשה לדפי אינטרנט להיות הרבה יותר רספונסיביים. אנחנו נלמד בהרחבה על נושא זה בהמשך. 

+ +
    +
  1. על מנת להתחיל, אנחנו הולכים לאחסן את ה-URL של ה-JSON שאנחנו נרצה לקבל בתוך משתנה. הוסיפו את הקוד הבא בתחתית הקוד של JavaScript שברשותכם:
  2. +
  3. +
    var requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
    +
  4. +
  5. על מנת ליצור בקשה, אנחנו צריכים ליצור אובייקט בקשה חדשה מה-constructor בשם XMLHttpRequest, באמצעות שימוש במילה השמורה new. הוסיפות את הקוד הבא מתחת לשורה האחרונה: +
    var request = new XMLHttpRequest();
    +
  6. +
  7. כעת, אנחנו צריכים לפתוח בקשה חדשה לאובייקט בקשה שיצרנו באמצעות המתודה ()open. הוסיפו את הקוד הבא: +
    request.open('GET', requestURL);
    + +

    מתודה זו מקבל לפחות שני פרמטרים - וניתן להזין עוד פרמטרים אופציונליים. הפרמטרים שאנחנו חייבים לציין בעבור הדוגמא הזו הם:

    + +
      +
    • סוג המתודה של HTTP שאנחנו נרצה לבצע בבקשת השרת - במקרה שלנו זו תהיה GET, שכן אנחנו רוצים לקבל מידע כלשהו. 
    • +
    • ה-URL שאנחנו נבצע אליו בקשה - זהו ה-URL שבו מאוחסן קובץ ה-JSON שלנו. 
    • +
    +
  8. +
  9. כעת, הוסיפו את השורות הבאות  - בשורות אלו אנחנו מגדירים את ה-responseType ל-JSON, כך שה-XHR יודע שהשרת יחזיר לנו JSON, ושמאחורי הקלעים תבוצע לו המרה לאובייקט JavaScript. בשורה השנייה אנחנו שולחים את הבקשה באמצעות מתודת ()send: +
    request.responseType = 'json';
    +request.send();
    +
  10. +
  11. החלק האחרון של הקוד הרשום להלן הוא בעצם המתנה לקבלת תגובה מהשרת, וביצוע פעולה איתה. הוסיפו את הקוד הבא מתחת לקוד הנוכחי שלכם: +
    request.onload = function() {
    +  var superHeroes = request.response;
    +  populateHeader(superHeroes);
    +  showHeroes(superHeroes);
    +}
    +
  12. +
+ +

כאן אנחנו מאחסנים את התגובה לבקשה לשלנו (הזמינה בפרופ׳ response ) בתוך משתנה שנקרא superHeroes. המשתנה עכשיו מכיל את האובייקט JavaScript שמבוסס על ה-JSON. לאחר מכן אנחנו מעבירים את אותו אובייקט כארגומנט לשתי קריאות פונקציות - הראשונה תמלא את ה-<header> עם המידע הנכון, ואילו השניה תיצור לנו כרטיס מידע בעבור כל ״גיבור״ בקבוצה ותכניס את הכרטיס הזה לתוך <section>

+ +

עטפנו את הקוד הזה בתוך מטפל אירוע - event handler - שירוץ ברגע שהאירוע load נוצר על האובייקט request (ראו onload) - זה מכיוון שהאירוע load נוצר כאשר התגובה מהשרת הוחזרה בהצלחה. ביצוע של דבר זה מבטיח לנו שה-request.response יהיה זמין בוודאות כשנרצה לעשות משהו איתו.

+ +

מילוי של מידע ב-header

+ +

כעת, כשהשגנו את המידע ב-JSON והמרנו אותו לאובייקט JavaScript, אנחנו יכולים לעשות בו שימוש באמצעות כתיבה של הפונקציות שציינו למעלה. ראשית, הוסיפו את הפונקציות הרשומות מטה מתחת לקוד הנוכחי שלכם: 

+ +
function populateHeader(jsonObj) {
+  var myH1 = document.createElement('h1');
+  myH1.textContent = jsonObj['squadName'];
+  header.appendChild(myH1);
+
+  var myPara = document.createElement('p');
+  myPara.textContent = 'Hometown: ' + jsonObj['homeTown'] + ' // Formed: ' + jsonObj['formed'];
+  header.appendChild(myPara);
+}
+ +

אנחנו קראנו לפרמטר בשם jsonObj, על מנת להזכיר לעצמנו שזהו בעצם אובייקט JavaScript שמקורו ב-JSON. ראשית, יצרנו אלמנט {{HTMLElement("h1")}} עם ()createElement, והשמנו את ה-textContent שיהיה שווה לפרופ׳ squadName של האובייקט, ולאחר מכן שייכנו אותו ל-header באמצעות ()appendChild

+ +

לאחר מכן עשינו פעולה דומה בעבור הפסקה - p: יצרנו אותה, השמנו את ה-textContent שלה ולאחר מכן הוספנו אותה ל-header. ההבדל היחיד הוא שהטקסט שלה הוא שרשור של מחרוזות המכילות את הפרופ׳ homeTown ו-formed של האובייקט jsonObj.

+ +

יצירה של כרטיסי המידע ״hero״

+ +

כעת, הוסיפו את הפונקציה הבאה מתחת לקוד הנוכחי, אשריוצרץ ומצגיה את כרטיסי המידע של ה-hero: 

+ +
function showHeroes(jsonObj) {
+  var heroes = jsonObj['members'];
+
+  for (var i = 0; i < heroes.length; i++) {
+    var myArticle = document.createElement('article');
+    var myH2 = document.createElement('h2');
+    var myPara1 = document.createElement('p');
+    var myPara2 = document.createElement('p');
+    var myPara3 = document.createElement('p');
+    var myList = document.createElement('ul');
+
+    myH2.textContent = heroes[i].name;
+    myPara1.textContent = 'Secret identity: ' + heroes[i].secretIdentity;
+    myPara2.textContent = 'Age: ' + heroes[i].age;
+    myPara3.textContent = 'Superpowers:';
+
+    var superPowers = heroes[i].powers;
+    for (var j = 0; j < superPowers.length; j++) {
+      var listItem = document.createElement('li');
+      listItem.textContent = superPowers[j];
+      myList.appendChild(listItem);
+    }
+
+    myArticle.appendChild(myH2);
+    myArticle.appendChild(myPara1);
+    myArticle.appendChild(myPara2);
+    myArticle.appendChild(myPara3);
+    myArticle.appendChild(myList);
+
+    section.appendChild(myArticle);
+  }
+}
+ +

לשם התחלה, אחסנו את הפרופ׳ members של אובייקט ה-JavaScript בתוך משתנה חדש. מערך זה מכיל מספר אובייקטים שמכילים את המידע בעבור כל hero. 

+ +

לאחר מכן, השתמשנו בלולאת for על מנת לעבור על כל אובייקט בתוך מערך זה. בעבור כל אובייקט במערך, עשינו את הדברים הבאים: 

+ +
    +
  1. יצרנו מספר אלמנטים חדשים: <article><h2>, שלוש <p>, ו-<ul>.
  2. +
  3. קבענו ש- <h2> יכיל את הערך הנוכחי של ה-name של ה-hero.
  4. +
  5. מילאנו את שלושת ה-p עם secretIdentity, age ושורה עם הטקסט "Superpowers:".
  6. +
  7. אחסנו את הפרופ׳ powers בתוך משתנה חדש שנקרא superPowers - זה מכיל מערך שמציג את ה-superpowers הנוכחיים.
  8. +
  9. השתמשנו בלולאת for שוב על מנת לעבור על כל ה-superpowers הנוכחיים של hero - בעבור כל אחד יצרנו אלמנט <li>, והכנסו את ה-superpower לתוכו ולאחר מכן שמנו את ה-listItem בתוך <ul> באמצעות ()appendChild.
  10. +
  11. לבסוף, שייכנו את <h2>, <p> ו-<ul> לתוך <article> (myArticle) ולאחר מכן שייכנו את <article> לתוך <section>. הסדר שבו דברים משוייכים הוא חשוב שכן כך הם יוצגו על גבי הדף.
  12. +
+ +
+

לתשומת לב: אם אתם נתקלים בבבעיה, ראו את הקוד המקור ב-heroes-finished.html או כ-דף אינטרנט

+
+ +
+

לתשומת לב:  אם אתם מתקשים בעניין ה-dot/bracket notation שאנו משתמשים כדי לגשת לאובייקט JavaScript, אולי יעזור לכם לפתוח את הקובץ superheroes.json בלשונית אחרת או בעורך הקוד שלכם, ולהסתכל עליו תוך כדי מעבר על הקוד שלנו. בנוסף, שקלו לעשות חזרה על המאמר שלנו בנושא אובייקטים - עקרונות יסוד.

+
+ +

המרה בין אובייקטים וטקסט

+ +

הדוגמא למעלה הייתה יחסי פשוטה במונחים של לגשת לאובייקט JavaScript, מכיוון שקבענו שבקשת ה-XHR שלנו תמיר את התגובת JSON ישירות לאובייקט JavaScript באמצעות: 

+ +
request.responseType = 'json';
+ +

לפעמים אנחנו נקבל מחרוזת JSON לא מעובדת, ואנחנו נצטרך להמיר אותה לאובייקט בעצמנו. וכאשר אנחנו נרצה לשלוח אובייקט JavaScript ברשת, אנחנו נצטרך להמיר אותו ל-JSON (מחרוזת) לפני השליחה שלו. למזלנו, שתי בעיות אלו כל כך נפוצות, שקיים אובייקט בשם JSON הזמין בכל הדפדפנים, המכיל שתי מתודות: 

+ + + +

אתם יכולים לראות את הראשון בפעולה בקובץ -heroes-finished-json-parse.html - הוא עושה בדיוק את אותו הדבר כמו בדוגמא שבנינו קודם, רק שאנחנו קבענו שה-XHR יחזיר טקסט JSON גולמ, ואז השתמשנו ב-()parse על מנת להמיר אותו לאובייקט JavaScript זה הקוד הרלוונטי:

+ +
request.open('GET', requestURL);
+request.responseType = 'text'; // now we're getting a string!
+request.send();
+
+request.onload = function() {
+  var superHeroesText = request.response; // get the string from the response
+  var superHeroes = JSON.parse(superHeroesText); // convert it to an object
+  populateHeader(superHeroes);
+  showHeroes(superHeroes);
+}
+ +

כפי שאתם יכולים לנחש, ()stringify עובד בדרך ההפוכה. נסו להזין את השורות הבאות לקונסולה:

+ +
var myJSON = { "name": "Chris", "age": "38" };
+myJSON
+var myString = JSON.stringify(myJSON);
+myString
+ +

כאן יצרנו אובייקט JavaScript ואז המרנו אותו למחרוזת JSON באמצעות ()stringify - ושמרנו את הערך שחזר במשתנה חדש. 

+ +

לסיכום

+ +

במאמר זה, ניסינו להעניק לכם מדריך פשוט כיצד להשתמש ב-JSON בתוכנויות שלנו, כולל כיצד ליצור ולהמיר JSON, וכיצד לגשת למידע המאוחסן בתוכו. במאמר הבא אנחנו נסתכל על פרקטיקות ביצירת אובייקטים ב-JavaScript.

+ +

ראו גם

+ + + +

{{PreviousMenuNext("Learn/JavaScript/Objects/Inheritance", "Learn/JavaScript/Objects/Object_building_practice", "Learn/JavaScript/Objects")}}

+ +

In this module

+ + diff --git a/files/he/learn/javascript/objects/object-oriented_js/index.html b/files/he/learn/javascript/objects/object-oriented_js/index.html new file mode 100644 index 0000000000..63f83aa94d --- /dev/null +++ b/files/he/learn/javascript/objects/object-oriented_js/index.html @@ -0,0 +1,275 @@ +--- +title: Object-oriented JavaScript for beginners +slug: Learn/JavaScript/Objects/Object-oriented_JS +translation_of: Learn/JavaScript/Objects/Object-oriented_JS +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Objects/Basics", "Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects")}}
+ +

לאחר שסיימנו עם עקרונות היסוד, כעת אנחנו נתמקד על- object-oriented JavaScript (OOJS) — מאמר זה נועד להעניק מבט בסיסי של תיאוריית object-oriented programming (OOP) ולאחר מכן נחקור כיצד JavaScript מחקה (מלשון חיקוי) מחלקות אובייקטים באמצעות פנקציה בנאית (constructor functions), וכיצד אנחנו יכולים ליצור ״מופעי״ אובייקטים

+ + + + + + + + + + + + +
ידע מוקדם:Basic computer literacy, a basic understanding of HTML and CSS, familiarity with JavaScript basics (see First steps and Building blocks) and OOJS basics (see Introduction to objects).
מטרה:להבין את בסיס התיאוריה שעומדת מאחורי תכנות מונחה עצמים, וכיצד זה מתקשר ל- JavaScript ("everything is an object"), ולהבין כיצד ליצור constructors ו- object instances.
+ +

Object-oriented programming — הבסיס

+ +

לשם ההצלחה, ננסה ללהעניק לכם נקודת מבט מופשטת, מלמעלה, של מה זה בעצם תכנות מונחה עצמים - Object-oriented programming (OOP). אנחנו אומרים מופשט מכיוון ש-0000 יכול להיות מורכב מאוד ופירוט של כל התיאוריה רוב הסיכויים תבלבל אתכם. הרעיון הבסיסי של OOP הוא שאנחנו משתמשים באובייקטים על מנת לדמות דברים אמיתיים מהעולם האמיתי שנרצה לכלול בתוך התוכנית שלנו, ו/או להעניק דרך פשוטה לגשת לפונקציונליות מסויימת, שבדרכים אחרות היה פשוט בלתי אפשרי או מסובך מאוד.

+ +

אובייקטים יכולים להכיל מידע וקוד הקשורים זה לזה, אשר מייצדים מידע אודות הדבר שנאחנו מנסים לדמות, ופונקציונליות או התנהגות שאנחנו רוצים שיהיה לאובייקט שלנו. המידע של האובייקט, ולרוב גם הפונקציות שלו, יכולות להיות מאוחסות בצורה מסודרת - (המילה המקצועית היא encapsulated - בתוך האובייקט (וניתן לתת להם שמות שיהוו הפניה לאותם ערכים, ולפעמים זה נקרא namespace), וכך נהיה פשוט לבנות ולגשת אליהם. אובייקטים גם לרוב משמשים כמאחסני מידע שאנחנו יכולים לשלוח בקלות ברשת.

+ +

הגדרה של טמפלייט של אובייקט

+ +

ננסה לחשוב על תוכנית פשוטה אשר מציגה מידע על תלמידים ועל מורים בבית ספר. אנחנו נסתכל על דוגמא זו ועל תיאוריית oop באופן כללי, מבלי להתייחס לשפת תכנות מסויימת.

+ +

על מנת להתחיל, אנחנו נחזור לאובייקט Person מהמאמר הקוד אובייקטים - עקרונות יסוד, אשר מגדיר את המידע והפונקציונליות הגנריות של בן אדם, של person. יש הרבה דברים שאנחנו יכולים לדעת על אדם (כתובת, גובה, מידת נעליים וכד׳), אבל במקרה שלנו אנחנו מעונינים להראות את השם, גיל, מין תחומי עניין שלהם, ואנחנו רוצים שתאפשר לנו לכתוב הקדמה קצרה עליהם, בהתבסס על המידע שיש לנו ולאפשר לאותו אובייקט להגיד שלום בצורה כלשהי. זה בעצם נקרה abstraction — יצירת מודל פשוט של משהו מורכב יותר אשר מייצג את האספקטיים החשובים ביותר בדרך כזו שניתן לעבוד איתה בתוכנית שלנו ולצרכי התוכנית שלנו.

+ +

+ +

יצירת אובייקטים

+ +

מהמחלקה שלנו אנחנו יכולים ליצור מופעי אובייקט - object instances — אלו בעצם אובייקטים המכילים את המידע והפונקציונליות שהוגדרו ב-מחלקה. מהמחלקה Person שלנו, אנחנו יכולים ליצור כמה אנשים בפועל:

+ +

+ +

כאשר נוצר מופע אובייקט ממחלקה, ה- constructor function של אותה מחלקה מורץ על מנת ליצור את האובייקט החדש. תהליך זה של יצירת מופע אובייקט ממחלקה נקרא instantiation — ומופע האובייקט שנוצר, האובייקט שנוצר, אנו אומרים שהוא instantiated מהמחלקה

+ +

Specialist classes

+ +

במקרה שלנו אנחנו לא רוצים אנשים שנראים אותו דבר - אנחנו רוצים מורים וסטודנטים, אשר הם בעלי מאפיינים ספיצפיים של בני אדם. ב-OOP, אנחנו יכולים ליצור מחלקות חדשות בהתבסס על מחלקות קיימות - אלו נקראים - child classes והם יכולים לרשת, ירושה  של מידע ומאפיינים של  קלאס האב שלהם, כך שאנחנו יכולים להשתמש בפונקציונליות שמשותפת לכל האובייקטים באמצעות אותה הורשה, מבלי שנצטרף לכתוב אותה מחדש בכל פעם. כאשר אנחנו צריכים להעניק תכונה או פונקציונליות פרטנית לאובייקט, אנחנו יכולים להגדיר אותם על אותו אובייקט באופן פרטני.

+ +

+ +

זהו מאוד שימושי - מורים וסטודנטים חולקים מאפיינים בסיסיים כמו שם, גיל, מין כך שזה יהיה נוח אם נוכל להגדיר את המאפיינים הללו פעם אחת בלבד. אנחנו גם יכולים להגדיר מאפיינים דומים באופן נפרד, במחלקות שונות, כך שכל מאפיין שכזה יהיה ב-namespace אחר. לדוגמא,הברה של סטודנט יכולה להיות שונה מהברכה של מורה. כך לדוגמא, הברכה של סטודנט תהיה "Yo, I'm [firstName]" (e.g Yo, I'm Sam), בעוד הברכה של מורה תהיה "Hello, my name is [Prefix] [lastName], and I teach [Subject]." (e.g Hello, My name is Mr Griffiths, and I teach Chemistry).

+ +
+

לתשומת לב: המילה הרשמית לאפשרות לשכפל אובייקטים ולהחיל עליהם את אותה פונקציונליות נקראת polymorphism. רק למקרה ותהיתם

+
+ +

אנחנו יכולים ליצור מופעי אובייקטים חדשים מה-child classes. לדוגמא:

+ +

+ +

בהמשך המאמר, אנחנו נסתכל כיצד תיאורית oop באה לידי ביטוי ב-JavaScript.

+ +

Constructors ו- object instances

+ +

JavaScript  משתמש בפונקציות מיוחדות שנקראות constructor functions על מנת להגדיר ול initialize אובייקטים ואת המאפיינים שלהם. זה שימושי מאוד מכיוון שאנחנו ניתקל בסיטואציות שבהן אנחנו לא יודעים כמה אובייקטים אנחנו נרצה או נצטרף ליצור. constructors מאפשרים לנו ליצור אובייקטים כמה שנרצה בדרך אפקטיבית, וך צירוף המידע והפונקציות שלהם ככל שנרצה.

+ +

נחקור כעת יצירה של מחלקות באמצעות constructors ויצירה של מופעי אובייקט מהם ב-JavaScript. ראשית, אנא צרו עותק של oojs.html

+ +

דוגמא פשוטה

+ +
    +
  1. נתחיל בכך שנסתכל כיצד אנחנו יכולים להגדיר person באמצעות פונקציה רגילה. הוסיפו את הפונקציה הזו לתוך אלמנט script : + +
    function createNewPerson(name) {
    +  var obj = {};
    +  obj.name = name;
    +  obj.greeting = function() {
    +    alert('Hi! I\'m ' + obj.name + '.');
    +  };
    +  return obj;
    +}
    +
  2. +
  3. כעת אנחנו יכולים ליצור person חדש באמצעות קריאה לפונקציה זו - נסו להזין אתהקוד הבא בקונסולה: +
    var salva = createNewPerson('Salva');
    +salva.name;
    +salva.greeting();
    + זה עובד בצורה טובה, אבל קצת מפותלת. אם אנחנו יודעים שאנחנו רוצים ליצור אובייקט, מדוע אנחנו צריכים ליצור במפורש אובייקט ריק בהתחלה ולהחזיר אותו? למרבה המזל, javascript מעניקה לנו קיצור שימושי פונקציה בנאית- constructor functions - בואו ניצור אחת יחד:
  4. +
  5. החליפו את הפונקציה הקודמת עם הפונקציה הנוכחית: +
    function Person(name) {
    +  this.name = name;
    +  this.greeting = function() {
    +    alert('Hi! I\'m ' + this.name + '.');
    +  };
    +}
    +
  6. +
+ +

ה-constructor function היא הגרסה של javascript למחלקות. שימו לב שיש לה את כל המאפיינים שאנחנו נצפה לראות בפונקציה, למרות שהיא לא מחזירה שום דבר או יוצרת אובייקט באופן מפורש - היא בסך הכל מגדירה מפתחות ומתודות. אנו משתמשים במילה השמורה this — זה בעיקרון אומר שבכל פעם שנוצר מופע אובייקט, ה- name property יהיה שווה לערך של name value שהועבר לתוך ה- constructor, והמתודה greeting() תשתמש באותם ערכים שהועברו ל- constructor.

+ +
+

שימו לב:שם של constructor function בדרך כלל מתחיל עם אות גדולה - זו מוסכמה מקובלת על מנת לזהות בקלותconstructor functions קוד שלנו.

+
+ +

אז כיצד אנחנו קוראים ל-constructor function על מנת ליצור אובייקטים?

+ +
    +
  1. הוסיפו את השורות הבאות מתחת לקוד הקודם שהוספתם: +
    var person1 = new Person('Bob');
    +var person2 = new Person('Sarah');
    +
  2. +
  3. שמרו ורעננו את הדף ולאחר מכן הזינו את השורות הבאות בקונסולה: +
    person1.name
    +person1.greeting()
    +person2.name
    +person2.greeting()
    +
  4. +
+ +

אתם תראו שאנחנו יצרנו שני אובייקטים חדשים, כאשר כל אחד מהם נשמר תחת שם אחר — כאשר אנחנו רוצים לגשת למפתחות ולמתודות שלהם, אנחנו צריכים להתחיל עם קריאה ל person1 או ל- person2; הפונקציונליות המאוחסנת בהם ארוזה בצורה מסודרת כך שהיא תתנגש עם פונקציונליות אחרת. יחד עם זאת, יש להם את אותו מפתח name  ואת אותה מתודת greeting() שזמינה עבורה. שימו לב שהם משתמשים בערך של ה - name שניתן להם כאשר הם נוצרו. זו אחת מהסיבות מדוע זה מאוד חשוב להתשמש במילה this, כך שהם ישתמשו בערכים שלהם ולא בערכים אחרים.

+ +

נסתכל שוב על הקריאות ל- constructor שוב:

+ +
var person1 = new Person('Bob');
+var person2 = new Person('Sarah');
+ +

בכל אחת מהקריאות, המילה השמורה new משמשת על מנת להגיד לדפדפן שאנחנו רוצים ליצוא מופע אובייקט חדש, ולאחר מכן יש את שם הפונקציה עם הפרמטרים הרלוונטיים בתוך הסוגריים והתוצאה של אותה פונקציה, של אותה constructor function, מאוחסנת בתוך משתנה - זה דומה מאוד לאיך שפונקציה רגילה מופעלת או לאיך שקוראים לפונקציה רגילה. כל מופע אובייקט שכזה נוצר בהתאם להגדרה של ה-constructor function:

+ +
function Person(name) {
+  this.name = name;
+  this.greeting = function() {
+    alert('Hi! I\'m ' + this.name + '.');
+  };
+}
+ +

לאחר שהאובייקטים החדשים נוצרו, המשתנים person1 ו- person2 מכילים את האובייקטים הבאים:

+ +
{
+  name: 'Bob',
+  greeting: function() {
+    alert('Hi! I\'m ' + this.name + '.');
+  }
+}
+
+{
+  name: 'Sarah',
+  greeting: function() {
+    alert('Hi! I\'m ' + this.name + '.');
+  }
+}
+ +

שימו לב שכאשר אנחנו קוראים ל-constructor function שלנו, אנחנו מגדירים את המתודה greeting() בכל פעם - משהו שאינו אידיאלי. על מנת להימנע מכך, אנחנו נגדיר פונקציות שהוא בתבנית האב - אנו נגע בנושא זה בהמשך.

+ +

יצירת ה-constructor הסופי שלנו

+ +

הדוגמא שהסברנו למעלה הייתה דוגמא פשוטה שנועדה רק לסבר לנו את האוזן. כעת, ניצור את ה-constructor function code>Person() הסופי שלנו.

+ +
    +
  1. הסירו את הקוד שהכנסתם עד עכשיו, והוסיפו את ה - constructor הזה - הוא בעצם אותו דבר כמו בדוגמא למעלה, רק קצת יותר מורכב: : +
    function Person(first, last, age, gender, interests) {
    +  this.name = {
    +     first : first,
    +     last : last
    +  };
    +  this.age = age;
    +  this.gender = gender;
    +  this.interests = interests;
    +  this.bio = function() {
    +    alert(this.name.first + ' ' + this.name.last + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');
    +  };
    +  this.greeting = function() {
    +    alert('Hi! I\'m ' + this.name.first + '.');
    +  };
    +}
    +
  2. +
  3. כעת, הוסיפו את הקוד הבא מתחת, על מנת ליצור מופעי אובייקט מ-constructor: +
    var person1 = new Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']);
    +
  4. +
+ +

אתם תראו שאנחנו יכולים לגשת לכל אחד מהמפתחות והמתודות בדיוק כפי שיכלנו לפני כן - נסו להזין את הקוד הבא בקונסולה:

+ +
person1['age']
+person1.interests[1]
+person1.bio()
+// etc.
+ +
+

לתשומת לב: אם אתם נתקלים בבעיות, נסו להשוות את הקוד שלכם לקוד שלנו - oojs-class-finished.html או ראו את דף האינטרנט.

+
+ +

תרגולים נוספים

+ +

על מנת להתחיל, הוסיפו כמה אובייקטים נוספים משלכם, ונסו לקבל או לקבוע את המידע שלהם.

+ +

בנוסף, יש מספר בעיות עם המתודה bio() — הפלט שלה תמיד יציג פלט בלשון זכר, למרות ש-person הוא נקבה. והמתמודה גם תציג רק שני תחומי עניין, אפילו אם בתוך המערך interests יש יותר תחומי עניין. האם אתם יכולים לתקן את זה ב-constructor שלנו? אם יכולים לשים כל קוד בתוך הconstructor (אתם כנראה תצרו משפטי תנאי ולולאה). חשבו כיצד המשפטים אמורים להיראות בצורה שונה כאשר מדובר במין שונה ומה עושים כאשר מספר תחומי העניין הוא 1, 2 או יותר מ-2.

+ +
+

לתשומת לב: אם אתם נתקעים, ראו את התשובה ב- GitHub repo או בדף היאנטרנט) — אך נסו בעצמכם לפני כן

+
+ +

דרכים נוספות ליצירת מופעי אובייקט - ליצירת אובייקטים חדשים

+ +

עד עכשיו ראינו שתי דרכים ליצירת מופעי אובייקט — הצהרה על אובייקט ליטראלי, ובאמצעות שימוש ב - constructor function (כפי שראינו למעלה).

+ +

ישנם דרכים נוספים ואנחנו נרצה להציג לכם אותם על מנת שתכירו אותם במידה ותיתקלו בהם בהמשך הדרך

+ +

The Object() constructor

+ +

ראשית, אתם יכולים לעשות שימוש ב constructor Object() על מנת ליצור אובייקט חדש. כן, גם אובייקטים גנריים יש להם constructor, אשר יוצר אובייקט ריק.

+ +
    +
  1. נסו להזין את הקוד הבא לתוך הקונסולה: +
    var person1 = new Object();
    +
  2. +
  3. קוד זה מאחסן בעצם אובייקט ריק בתוך המשתנה person1 .אנחנו יכולים להוסיף מפתחות ומתודות לאובייקט זה באמצעות שימוש ב- dot או dot; נסו להזין את הדוגמאות הבאות בקונסולה: +
    person1.name = 'Chris';
    +person1['age'] = 38;
    +person1.greeting = function() {
    +  alert('Hi! I\'m ' + this.name + '.');
    +};
    +
  4. +
  5. אתם גם יכולים להעביר object literal ל- Object() constructor כפרמטר, על מנת למלא מראש את הפרופ׳ והמתודות: נסו להזין את הקוד הבא בקונסולה: +
    var person1 = new Object({
    +  name: 'Chris',
    +  age: 38,
    +  greeting: function() {
    +    alert('Hi! I\'m ' + this.name + '.');
    +  }
    +});
    +
  6. +
+ +

שימוש במתודת create()

+ +

Constructors יכולים לעזור להעניק סדר לקוד שלנו - אנחנו יכולים ליצור את הconstructors במקום אחד ואז ליצור מופעים שלהם כמה שנרצה, במקום אחר, וזה יהיה ברור מאיפה הם נוצרוץ

+ +

יחד עם זאת, ישנם מפתחים אשר מעדיפים ליצור מופעי אובייקט מבלי ליצור תחילה constructors, במיוחד אם אתם יוצרים רק מספר קטם של מופעי אובייקט. ל-JavaScript יש מתודה מובנת שנקראת create() אשר מאפשרת לנו לעשות זאת. עם מתודה זו, אנחנו יכולים ליצור אובייקט חדש, בהתבסס על אובייקט קיים.

+ +
    +
  1. העלו את התרגיל שסיימתם בתרגול הקודם לדפדפן והוסיפו את הקוד הבא לקונסולה: : +
    var person2 = Object.create(person1);
    +
  2. +
  3. כעת נסו להזין את הקוד הבא בקונסולה: +
    person2.name
    +person2.greeting()
    +
  4. +
+ +

אתם תראו ש-person2 נוצר בהתבסס על person1 - יש לו את אותם פרופ׳ ומתודות שזמינות עבורו.

+ +

הגבלה אחת שיש בשימוש עם מתודת create() היא שדפדפן IE8 does לא תומך בה. אז constructors יכולים להיות דרך רלוונטם במידה ואתם צריכים לתמוך בגרסה זו.

+ +

אנו נחקור את המתודה create() בפרטי פרטים בהמשך הקורס.

+ +

לסיכום

+ +

מאמר זה העניק לכם מבט מופשט על תיאוריית פיתוח מונחה עצמים - זה לא הסיפור המלא כמובן, אבל זה נועד לתת לכם את הרעיון שאיתו אנחנו ממשיכים. בנוסף, התחלנו לגלות כיצד אנחנו יכולים ליצור מופעי אובייקט, או אובייקטים חדשים, בדרכים שונות.

+ +

במאמר הבא אנחנו נחקור את נושא JavaScript object prototypes.

+ +

{{PreviousMenuNext("Learn/JavaScript/Objects/Basics", "Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects")}}

+ +

במודול זה

+ + diff --git a/files/he/learn/javascript/objects/object_prototypes/index.html b/files/he/learn/javascript/objects/object_prototypes/index.html new file mode 100644 index 0000000000..0afe0ef67d --- /dev/null +++ b/files/he/learn/javascript/objects/object_prototypes/index.html @@ -0,0 +1,283 @@ +--- +title: Object prototypes +slug: Learn/JavaScript/Objects/Object_prototypes +translation_of: Learn/JavaScript/Objects/Object_prototypes +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects/Inheritance", "Learn/JavaScript/Objects")}}
+ +

Prototypes - אבי טיפוס, זה המנגנון שבאמצעותו אובייקטים של javascript יורשים מאפיינים אחד מהשני. במאמר זה אנחנו נסביר כיצד שרשראות אבי טיפוס - (prototype chains) עובדות ונסתכל כיצד מאפיין (property) בשם prototype יכול לשמש עבור הוספת מתודות ל-constructors קיימים.

+ + + + + + + + + + + + +
ידע מוקדם: +

הבנה של פונקציות ב-JavaScript, הכרות עם הבסיס של JavaScript (ראו את המאמר צעדים ראשונים ב-צעדים ראשונים ב-JavaScript ו-אבני הבניין של JavaScript) וכן הבסיס של תכנות מונחה עצמית ב-JavaScript (ראו אובייקטים - עקרונות יסוד).

+
מטרה:הבנה של JavaScript object prototypes, כיצד שרשראות prototype עובדות, וכיצד להוסיף מתודות חדשות לתוך פרופ׳ בשם prototype .
+ +

שפה מבוססת אב-טיפוס?

+ +

JavaScript לעיתים קרובות מתוארת כשפה מונחית אבי-טיפוס (prototype-based language) - על מנת לאפשר הורשה, לאובייקטים יכול להיות אובייקט אב-טיפוס (prototype object), אשר מתפקד כאובייקט תבנית - אובייקט אב טיפוס אשר ממנו האובייקטים יכולים לירוש מתודות (methods) ומאפיינים (properties).

+ +

לאובייקט אב-הטיפוס (prototype), יכול להיות גם אובייקט אב-טיפוס משל עצמו, אשר ממנו הוא יורש מתודות (methods) ומאפיינים (properties) וכך הלאה. תהליך זה לרוב מוגדר כשרשרת אבי הטיפוס (prototype chain), אשר מסבירה מדוע לאובייקטים שונים יש מאפיינים ומתודות שזמינים עבורם, כאשר אלו בכלל הוגדרו באובייקטים אחרים. 

+ +

ליתר דיוק, המתודות והמאפיינים מוגדרים במאפיין (property) בשם prototype ב-constructor functions ולא באובייקטים עצמם שנוצרו (object instance).

+ +

ב-JavaScript, נוצר קשר בין האובייקט שנוצר (object instance) לבין אב הטיפוס/prototype שלו באמצעות ״הליכה״ על שרשרת אבי הטיפוס. אנו נוכל לראות את אב הטיפוס של אובייקט ב-property של האובייקט שנוצר בשם __proto__ . שם זה נגזר מ-prototype שמוגדר בכלל ב-constructor.  

+ +
+

לתשומת לב:  חשוב להבין שיש אבחנה בין אב הטיפוס של האובייקט  (object' s prototype) אשר זמין באמצעות (Object.getPrototypeOf(obj או באמצעות מאפיין __proto__לבין מאפיין (property) בשם אב-טיפוס (prototype) אשר נמצא ב-constructor functions. 

+ +

הראשון הוא מאפיין שיופיע על כל אובייקט שייווצר ויעיד מיהו אב הטיפוס של אותו אובייקט ואילו השני, אשר נמצא ב-constructor הוא בעצם מאפיין של אותו constructor. 

+
+ +

נסתכל על דוגמא על מנת להבין זאת לעומק.

+ +

הבנה של אובייקטים מסוג אב-טיפוס

+ +

נחזור לדוגמא הקודמת שבה סיימנו לכתוב את ה-constructor שלנו ()Person:

+ +

העלו את הדוגמא בדפדפן שלכם. אם אין לכם את הדוגמא עצמה או שהיא אינה עובדת, אנא השתמשו בדוגמא שלנו אשר נמצאת בקישור זה או בקוד המקור.

+ +

בדוגמא זו, אנחנו מגדירים את ה -constructor function שלנו כך:

+ +
function Person(first, last, age, gender, interests) {
+
+  // property and method definitions
+  this.first = first;
+  this.last = last;
+//...
+}
+ +

אנו יוצרים אובייקטים מה-constructor function שהגדרנו כך:

+ +
var person1 = new Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']);
+ +

אם תקלידו .person1 בקונסולה, אתם אמורים לראות שהדפדפן מנסה להשלים באופן אוטומטי אפשרויות הזמינות עבור אובייקט זה: 

+ +

+ +

ברשימה זו, אתם יכולים לראות את הפרופ׳ ומתודות שהוגדרו ב-constructor Person()name, age, gender, interests, bio, ו- greeting. בנוסף, אנחנו גם נראה פרופ׳ ומתודות נוספות - watch, valueOf וכד׳ - אלו מוגדרים בתבנית אב הטיפוס (prototype object) של ()Person, שזה  Object.

+ +

+ +

מה קורה כשאנחנו רוצים לקרוא למתודה, להפעיל מתודה על person1, אשר מוגדרת ב-Object?:

+ +
person1.valueOf()
+ +

המתודה הזו - ()Object.valueOf נורשת על ידי person1 בגלל שתבנית אב הטיפוס של האובייקט (הפונקציה ()Person) שיצר אותו היא  ()Object. המתודה ()valueOf מחזירה את הערך של האובייקט שהיא נקראה עליו: 

+ + + +
+

לתשומת לב: אנחנו רוצים להדגיש את העבודה שמתודות ופרופ׳ לא מועתקים מאובייקט אחד לשני ב-prototype chain - הם זמינים עבורם באצעות הליכה על prototype chain כפי שהסברנו למעלה..

+
+ +
+

לתשומת לב: אין דרך רשמית להיכנס לאובייקט אב הטיפוס של אובייקט בצורה ישירה  הקשרים שבין הפריטים בשרשרת מוגדר בתוך פרופ׳ פנימי - שנקרא [[prototype]] במסמכים של השפה - ראו גם {{glossary("ECMAScript")}}. 

+ +

מרבית הדפדפנים המודרניים מכילים פרופ׳ שזמין שנקרא בשם __proto__, אשר מכיל את האובייקט שהוא תבנית האב של האובייקט הרלוונטי. לדוגמא, נסו להזין person1.__proto__ ו- person1.__proto__.__proto__ לראות איך זה נראה. החל מ-ECMAScript 2015 אנחנו יכולים לגשת לאובייקט אב הטיפוס של אובייקט באמצעות Object.getPrototypeOf(obj).

+
+ +

The prototype property: היכן שמגדירים מה מורישים

+ +

אז, היכן הפרופ׳ והמתודות שמורישים מוגדרים? אם אנחנו מסתכלים על הדף Object, אנחנו נראה רשימה מצד של שמאל של פרופ׳ ומתודות - הרבה יותר מאלו שראינו שזמינות עבור person1. למה? מכיוון שחלקם הורשו ל-person1 וחלקם לא. 

+ +

כפי שהוסבר למעלה, אלו שנורשו הם אלו שמוגדרים במאפיין (property) בשם prototype - כלומר אלו הם שמתחילים עם .Object.prototype ולא אלו שרק מתחילים עם Object. הערך של המאפיין prototype הוא אובייקט, אשר בעצם הוא מאחסן את כל הפרופ׳ והמתודות שאנחנו רוצים להוריש לאובייקטים בהמשך ה-prototype chain.

+ +

כך לדוגמא, ()Object.prototype.watch ו- ()Object.prototype.valueOf זמינות עבור כל אובייקט שיירש מ-Object.prototype, כולל מופעים חדשים של אובייקטים מה-()constructor Person

+ +

לעומת זאת, ()Object.is ו-()Object.keys לדוגמא, לא מוגדרים בתוך () ולכן לא נוריש אותם לאובייקטים אשר יירשו מ-Object.prototype. הם מתודות ופרופ׳ אשר זמינים רק עבור ה-constructor Object עצמו. 

+ +
+

לתשומת לב:  זה נראה מוזר - כיצד יכולה להיות מתודה שמוגדרת על ה-constructor, שהיא בעצמה פונקציה? פונקציות הם גם סוג של אובייקט - ראו הדף בנושא ()Function להמשך פרטים.

+
+ +
    +
  1. אתם יכולים לבדוק את הפרופ׳ בשם ה-prototype של האובייקטים הנוכחיים שלנו - חזרו לדוגמא הקודמת והקלידו את הקוד הבא בקונסולה: +
    Person.prototype
    +
  2. +
  3. אתם לא תראו יותר מדי אפשרויות מכיוון שלא הגדרנו כלום בפרופ׳ בשם prototype של ה-constructor. כברירת מחדל, הפרופ׳ בשם prototype של ה-constructor תמיד מתחיל ריק.
  4. +
  5. כעת, נסו להזין את הקוד הבא: +
    Object.prototype
    +
  6. +
+ +

אתם תראו מספר גדול של מתודות שמוגדרות ב-property בשם prototype של Object, אשר זמינות עבור אובייקטים שירשו מ-Object כפי שהסברנו למעלה.

+ +

אתם תראו דוגמאות כאלו של שרשרת ההורשה - prototype chain inheritance בכל JavaScript - נסו לחפש אחר מתודות ופרופ׳ אשר מוגדרים בפרופ׳ של האובייקטים הגלובליים String, Date, Number, ו-Array. לכולם יש מס׳ מתודות ופרופ׳ שמוגדרות באותו prototype. זו הסיבה לדוגמא שכשאר אנחנו יוצרים מחרוזת בצורה הבאה:

+ +
var myString = 'This is my string.';
+ +

ל-myString ישר יש מספר מתודות שימושיות שזמינות עבורו כמו () split(), indexOf(), replace וכד׳. 

+ +
+

לתשומת לב: אנו ממליצים לקרוא את המדריך המעמיק שלנו בנושא - Using prototypes in JavaScript לאחר שהבנתם את החלק הזה. החלק הזה בכוונה נכתב בצורה פשוטה (יחסית) על מנת להסביר את הרעיון שעומד מאחורי הנושא.

+
+ +
+

חשוב: המאפיין (prototype (property הוא אחד מהחלקים המבלבלים ב-JavaScript. אתם עלולים לחשוב ש-this מצביע על האובייקט אב טיפוס של האובייקט הנוכחי, אבל הוא לא (זה אובייקט פנימי שניתן לגשת אליו באמצעות __proto__, זוכרים? ).

+ +

המאפיין prototype הוא בעצם property שמכיל אובייקט, אשר על אובייקט זה אנחנו מגדירים את המתודות והפרופ׳ שנרצו שיורשו.

+
+ +

שימוש במתודה ()create

+ +

מוקדם יותר ראינו כיצד מתודת ()Object.create יכולה לשמש על מנת ליצור אובייקט חדש:

+ +
    +
  1. לדוגמא, נסו להזין בקונסולה של הדוגמא הקודמת את הקוד הבא: +
    var person2 = Object.create(person1);
    +
  2. +
  3. מה ש-()create עושה בפועל היא ליצור אובייקט חדש מ-prototype מוגדר. כאן person2 מיוצר כאובייקט חדש באמצעות שימוש ב-person1 כאובייקט ה-prototype שלו, כאובייקט אב הטיפוס שלו. אתם יכולים לראות זאת באמצעות הזנת הקוד הבא בקונסולה:
  4. +
  5. +
    person2.__proto__
    +
  6. +
+ +

זה יחזיר לנו person1.

+ +

המאפיין (property) בשם constructor

+ +

לכל constructor function יש מאפיין (property) בשם prototype אשר הערך שלו הוא אובייקט. אותו אובייקט מכיל מאפיין (property) בשם constructor

+ +

המאפיין constructor הזה, מצביע ל-constructor function המקורית. כפי שתראו בהמשך, כאשר properties שמוגדרים על Person.prototype property, או באופן כללי, על המאפיין prototype של constructor function, שהוא בעצמו הוא אובייקט, הם נהיים זמינים עבור כל האובייקטים שייווצרו באמצעות ה-constructor בשם ()Person. המאפיין constructor זמין גם עבור האובייקט person1 וגם עבור האובייקט person2

+ +
    +
  1. לדוגמא, נסו להזין את השורות הבאות בקונסולה: +
    person1.constructor
    +person2.constructor
    + +

    שתיהן אמורות להחזיר לנו ה-Person() constructor, שכן היא מכילה את ה-״הגדרה״ המקורית של אובייקטים אלו. טריק חכם הוא שניתן לשים סוגריים רגילות () בסוף המאפיין constructor (ובתוך הסוגריים להכניס פרמרטים הנדרשים ל-constructor, ככל ונדרשים), וואז נוצר לנו אובייקט חדש מאותו constructor. ה-constructor הוא בעצם פונקציה אחרי הכל, אז אפשר לקרוא לפונקציה באמצעות שימוש ב-() כמו שאנחנו יודעים. רק חשוב לשים את המילה השמורה new לפני, על מנת להגדיר שאנחנו רוצים שיווצר אובייקט חדש ולהשתמש בפונקציה הזו כ-constructor של אותו אובייקט. 

    +
  2. +
  3. נסו להזין את הקוד הבא בקונסולה: +
    var person3 = new person1.constructor('Karen', 'Stephenson', 26, 'female', ['playing drums', 'mountain climbing']);
    +
  4. +
  5. כעת, נסו לגשת למתודות ולפרופ׳ של האובייקט החדש: +
    person3.name.first
    +person3.age
    +person3.bio()
    +
  6. +
+ +

זה עובד מצויין. אנחנו בדרך לא נשתמש באופציה שכזו, אבל זה יכול להיות שימושי כאשר אנחנו רוצים ליצור מופע אובייקט חדש ואין לנו הפנייה לקונסטרקטור המקורי בצורה פשוטה מכל סיבה שהיא. 

+ +

ה-property בשם constructor שימושי גם לדברים נוספים. לדוגמא, אם יש לנו אובייקט ואני רוצה להחזיר את שם ה-constructor שהוא מופע שלו, כלומר שבנה אותו, אנחנו יכולים להזין את הקוד הבא:

+ +
instanceName.constructor.name
+ +

נסו לדוגמא להזין את הקוד הבא:

+ +
person1.constructor.name
+
+ +
+

לתשומת לב:  הערך של constructor.name יכול להשתנות (כתוצאה מ-prototypical inheritance, binding, preprocessors, transpilers, etc. ועד), אז לדוגמאות מורכבות יותר, אנחנו נרצה להתשמש באופרטור instanceof במקום. 

+
+ +
    +
+ +

שינוי של הפרופ׳ בשם prototype - הוספה/הסרה של מתודות

+ +

נסתכל כעת על דוגמא לשינוי של ה-property בשם prototype שנמצא ב-constructor function - מתודות שיתווספו ל-prototype יהיו זמינות עבור כל האובייקטים שנוצרו מאותה constructor function. בנקודה הזו אנחנו נוסיף מתודות ל-property בשם prototypeשל constructor function שלנו, כך שכל מה שנגדיר במאפיין prototype יהיה זמין עבור האובייקטים שייווצרו ממנו. 

+ +
    +
  1. חזרו לדוגמא המופיע בקישור oojs-class-further-exercises.htm וצרו עותק מקומי של קוד המקור source code. מתחת לקוד הנוכחי של של JavaScript, הוסיפו את הקוד הבא, אשר יוצר מתודה חדשה במאפיין prototype של constructor function:
  2. +
  3. +
    Person.prototype.farewell = function() {
    +  alert(this.name.first + ' has left the building. Bye for now!');
    +};
    +
  4. +
  5. שמרו את הקוד והעלו את הדף בדפדפן, ונסו להזין את הקוד הבא : +
    person1.farewell();
    +
  6. +
+ +

אתם אמורים לקבל הודעה קופצת מסוג alert, המכילה את שם ה-person שהוגדר ב-constructor. זה מאוד שימוש, אבל מה שיותר שימושי זה שכל שרשרת ההורשה עודכנה באופן דינאמי ואוטומטי והפכה את המתודה הזו לזמינה עבור כל האובייקטים שנוצרו באמצעות אותה constructor function. 

+ +

חשבו על זה לרגע, בקוד שלנו אנחנו הגדרנו את ה-constructor function, ואז יצרנו אובייקט מאותה constructor function, ואז הוספנו מתודה נוספות ל-prototype של אותה constructor function: 

+ +
function Person(first, last, age, gender, interests) {
+
+  // property and method definitions
+
+}
+
+var person1 = new Person('Tammi', 'Smith', 32, 'neutral', ['music', 'skiing', 'kickboxing']);
+
+Person.prototype.farewell = function() {
+  alert(this.name.first + ' has left the building. Bye for now!');
+};
+ +

ומה שקרה זה שהמתודה שהגדרנו ()farewell נהייתה זמינה עבור person1 - והוא יכול לעשות בה שימוש, למרות שהוא הוגדר לפני שהגדרנו את המתודה החדשה. מגניב, לא?

+ +
+

לתשומת לב: אם אתם נתקלים בבעיות, ראו את הדוגמא פה או כדף אינטרנט.

+
+ +

יחד עם זאת, לעיתים נדירות נראה properties שמוגדרים ב-property הprototype מכיוון שהם לא ממש גמישים כשהם מוגדרים בצורה הזו. לדוגמא, ניתן להוסיף property בצורה הזו: 

+ +
Person.prototype.fullName = 'Bob Smith';
+ +

זה לא ממש מאפשר גמישות (שכן יכול להיות שקוראים לאובייקט person החדש בשם אחר), ולכן יהיה עדיף לבנות את המאפיין החדש בצורה הבאה: 

+ +
Person.prototype.fullName = this.name.first + ' ' + this.name.last;
+ +

יחד עם זאת, זה לא יעבוד שכן this יפנה לסקופ הגלובלי במקרה הנוכחי ולא לסקופ של הפונקציה. קריאה למאפיין זה תחזיר ערך של undefined undefined.

+ +

זה עובד מצוין על מתודה שהגדרנו למעלה ב-prototype מכיוון שהיא יושבת בתוך הסקופ של ה-function, והמתודה מועברת בתורה לסקופ של האובייקט שנוצר באמצעות constructor function. אז אולי נגדיר constant properties ב- prototype, כאלו שלא נשנה לעולם, אבל בכללי, זה עובד טוב יותר להגדיר properties בתוך ה-constructor. 

+ +

בעקרון, השימוש המקובל להגדרת אובייקטים הוא להגדיר את המאפיינים (properties) בתוך ה-constructor ואת המתודות בתוך ה-prototype. 

+ +

זה הופך הקוד לקל יותר לקריאה, שכן ה-constractor מכיל רק  את ההגדרות של properties ואילו המתודות מחולקות לבלוקים נפרדים. לדוגמא:

+ +
// Constructor with property definitions
+
+function Test(a, b, c, d) {
+  // property definitions
+}
+
+// First method definition
+
+Test.prototype.x = function() { ... };
+
+// Second method definition
+
+Test.prototype.y = function() { ... };
+
+// etc.
+ +

ניתן לראות שימוש בפועל בדוגמא school plan app של Piotr Zalewa.

+ +

לסיכום

+ +

מאמר זה כיסה את הנושא של JavaScript object prototypes, כולל כיצד prototype object chains מאפשרת לאובייקטים לירוש מתודות ופרופ׳ אחד מהשני, ראינו את ה-property בשם prototype וכיצד הוא יכול לשמש על מנת להוסיף מתודות ל-constructors וכן נושאים נוספים.

+ +

במאמר הבא אנחנו נראה כיצד ניתן להחיל הורשה של פונצקיונליות בין שני אובייקטים שניצור. 

+ +

{{PreviousMenuNext("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects/Inheritance", "Learn/JavaScript/Objects")}}

+ +

במודול זה

+ + diff --git a/files/he/learn/server-side/express_nodejs/index.html b/files/he/learn/server-side/express_nodejs/index.html new file mode 100644 index 0000000000..a8212504ce --- /dev/null +++ b/files/he/learn/server-side/express_nodejs/index.html @@ -0,0 +1,64 @@ +--- +title: Express web framework (Node.js/JavaScript) +slug: Learn/Server-side/Express_Nodejs +translation_of: Learn/Server-side/Express_Nodejs +--- +
{{LearnSidebar}}
+ +

Express is a popular unopinionated web framework, written in JavaScript and hosted within the Node.js runtime environment. This module explains some of the key benefits of the framework, how to set up your development environment and how to perform common web development and deployment tasks.

+ +

תנאים מוקדמים

+ +

לפני שתתחיל את המודל עליך להבין מה זה תכנות צד שרת ומה זה מסגרות אינטרנט (frameworks), מומלץ לקרוא על הנושא במדריך שלנו צעדים ראשונים לתכנות האתר בצד שרת. ידע כללי על מושגי תכנות ו- JavaScript מומלץ מאוד, אך אינו חיוני להבנת מושגי הליבה.

+ +
+

Note: This website has many useful resources for learning JavaScript in the context of client-side development: JavaScriptJavaScript Guide, JavaScript BasicsJavaScript (learning). The core JavaScript language and concepts are the same for server-side development on Node.js and this material will be relevant. Node.js offers additional APIs for supporting functionality that is useful in browserless environments (e.g., to create HTTP servers and access the file system), but does not support JavaScript APIs for working with the browser and DOM.

+ +

This guide will provide some information about working with Node.js and Express, and there are numerous other excellent resources on the Internet and in books — some of these linked from How do I get started with Node.js (StackOverflow) and What are the best resources for learning Node.js? (Quora).

+
+ +

מדריכים

+ +
+
מבוא-Node.js/Express
+
In this first Express article we answer the questions "What is Node?" and "What is Express?" and give you an overview of what makes the Express web framework special. We'll outline the main features and show you some of the main building blocks of an Express application (although at this point you won't yet have a development environment in which to test it).
+
Setting up a Node (Express) development environment
+
Now that you know what Express is for, we'll show you how to set up and test a Node/Express development environment on Windows, Linux (Ubuntu), and Mac OS X. Whatever common operating system you are using, this article should give you what you need to be able to start developing Express apps.
+
Express Tutorial: The Local Library website
+
The first article in our practical tutorial series explains what you'll learn and provides an overview of the "local library" example website we'll be working through and evolving in subsequent articles.
+
Express Tutorial Part 2: Creating a skeleton website
+
This article shows how you can create a "skeleton" website project, which you can then go on to populate with site-specific routes, templates/views, and databases.
+
Express Tutorial Part 3: Using a Database (with Mongoose)
+
This article briefly introduces databases for Node/Express. It then goes on to show how we can use Mongoose to provide database access for the LocalLibrary website. It explains how object schema and models are declared, the main field types, and basic validation. It also briefly shows a few of the main ways you can access model data.
+
Express Tutorial Part 4: Routes and controllers
+
In this tutorial we'll set up routes (URL handling code) with "dummy" handler functions for all the resource endpoints that we'll eventually need in the LocalLibrary website. On completion, we'll have a modular structure for our route handling code, that we can extend with real handler functions in the following articles. We'll also have a really good understanding of how to create modular routes using Express.
+
Express Tutorial Part 5: Displaying library data
+
We're now ready to add the pages that display the LocalLibrary website books and other data. The pages will include a home page that shows how many records we have of each model type and list and detail pages for all of our models. Along the way, we'll gain practical experience in getting records from the database and using templates.
+
Express Tutorial Part 6: Working with forms
+
In this tutorial we'll show you how to work with HTML Forms in Express, using Pug, and in particular how to write forms to create, update, and delete documents from the database.
+
Express Tutorial Part 7: Deploying to production
+
Now you've created an awesome LocalLibrary website, you're going to want to install it on a public web server so that it can be accessed by library staff and members over the Internet. This article provides an overview of how you might go about finding a host to deploy your website, and what you need to do in order to get your site ready for production.
+
+ +

ראה עוד

+ +
+
Installing LocalLibrary on PWS/Cloud Foundry
+
This article provides a practical demonstration of how to install LocalLibrary on the Pivotal Web Services PaaS cloud — this is a full-featured, open source alternative to Heroku, the PaaS cloud service used in Part 7 of the tutorial, listed above. PWS/Cloud Foundry is definitely worth checking out if you are looking for an alternative to Heroku (or another PaaS cloud service), or simply feel like trying something different. 
+
+ +

Adding more tutorials

+ +
+

All existing tutorials are listed above, but if you would like to extend this module, some other interesting topics to cover include:

+ + + +

An assessment for the module would also make a wonderful addition!

+
diff --git a/files/he/learn/server-side/express_nodejs/introduction/index.html b/files/he/learn/server-side/express_nodejs/introduction/index.html new file mode 100644 index 0000000000..31be2705c0 --- /dev/null +++ b/files/he/learn/server-side/express_nodejs/introduction/index.html @@ -0,0 +1,542 @@ +--- +title: Express/Node introduction +slug: Learn/Server-side/Express_Nodejs/Introduction +translation_of: Learn/Server-side/Express_Nodejs/Introduction +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/Server-side/Express_Nodejs/development_environment", "Learn/Server-side/Express_Nodejs")}}
+ +

In this first Express article we answer the questions "What is Node?" and "What is Express?", and give you an overview of what makes the Express web framework special. We'll outline the main features, and show you some of the main building blocks of an Express application (although at this point you won't yet have a development environment in which to test it).

+ + + + + + + + + + + + +
תנאים מוקדמים:Basic computer literacy. A general understanding of server-side website programming, and in particular the mechanics of client-server interactions in websites.
מטרה:To gain familiarity with what Express is and how it fits in with Node, what functionality it provides, and the main building blocks of an Express application.
+ +

הכירו את Node

+ +

Node (or more formally Node.js) is an open-source, cross-platform runtime environment that allows developers to create all kinds of server-side tools and applications in JavaScript. The runtime is intended for use outside of a browser context (i.e. running directly on a computer or server OS). As such, the environment omits browser-specific JavaScript APIs and adds support for more traditional OS APIs including HTTP and file system libraries.

+ +

From a web server development perspective Node has a number of benefits:

+ + + +

You can use Node.js to create a simple web server using the Node HTTP package.

+ +

Hello Node.js

+ +

The following example creates a web server that listens for any kind of HTTP request on the URL http://127.0.0.1:8000/ — when a request is received, the script will respond with the string: "Hello World". If you have already installed node, you can follow these steps to try out the example:

+ +
    +
  1. Open Terminal (on Windows, open the command line utility)
  2. +
  3. Create the folder where you want to save the program, for example, test-node and then enter it by entering the following command into your terminal:
  4. +
+ +
cd test-node
+ +
    +
  1. Using your favorite text editor, create a file called hello.js and paste the following code into it:
  2. +
+ +
// Load HTTP module
+const http = require("http");
+
+const hostname = "127.0.0.1";
+const port = 8000;
+
+// Create HTTP server
+const server = http.createServer((req, res) => {
+
+   // Set the response HTTP header with HTTP status and Content type
+   res.writeHead(200, {'Content-Type': 'text/plain'});
+
+   // Send the response body "Hello World"
+   res.end('Hello World\n');
+});
+
+// Prints a log once the server starts listening
+server.listen(port, hostname, () => {
+   console.log(`Server running at http://${hostname}:${port}/`);
+})
+
+ +
    +
  1. Save the file in the folder you created above.
  2. +
  3. Go back to the terminal and type the following command:
  4. +
+ +
node hello.js
+ +

Finally, navigate to http://localhost:8000 in your web browser; you should see the text "Hello World" in the upper left of an otherwise empty web page.

+ +

Web Frameworks

+ +

Other common web-development tasks are not directly supported by Node itself. If you want to add specific handling for different HTTP verbs (e.g. GET, POST, DELETE, etc.), separately handle requests at different URL paths ("routes"), serve static files, or use templates to dynamically create the response, Node won't be of much use on its own. You will either need to write the code yourself, or you can avoid reinventing the wheel and use a web framework!

+ +

Introducing Express

+ +

Express is the most popular Node web framework, and is the underlying library for a number of other popular Node web frameworks. It provides mechanisms to:

+ + + +

While Express itself is fairly minimalist, developers have created compatible middleware packages to address almost any web development problem. There are libraries to work with cookies, sessions, user logins, URL parameters, POST data, security headers, and many more. You can find a list of middleware packages maintained by the Express team at Express Middleware (along with a list of some popular 3rd party packages).

+ +
+

Note: This flexibility is a double edged sword. There are middleware packages to address almost any problem or requirement, but working out the right packages to use can sometimes be a challenge. There is also no "right way" to structure an application, and many examples you might find on the Internet are not optimal, or only show a small part of what you need to do in order to develop a web application.

+
+ +

Where did Node and Express come from?

+ +

Node was initially released, for Linux only, in 2009. The NPM package manager was released in 2010, and native Windows support was added in 2012. The current LTS release is Node v12.16.1 while the latest release is Node 13.11.0. This is a tiny snapshot of a rich history; delve into Wikipedia if you want to know more.

+ +

Express was initially released in November 2010 and is currently on version 4.17.1 of the API. You can check out the changelog for information about changes in the current release, and GitHub for more detailed historical release notes.

+ +

כמה פופלרי Node ו Express?

+ +

The popularity of a web framework is important because it is an indicator of whether it will continue to be maintained, and what resources are likely to be available in terms of documentation, add-on libraries, and technical support.

+ +

There isn't any readily-available and definitive measure of the popularity of server-side frameworks (although sites like Hot Frameworks attempt to assess popularity using mechanisms like counting the number of GitHub projects and StackOverflow questions for each platform). A better question is whether Node and Express are "popular enough" to avoid the problems of unpopular platforms. Are they continuing to evolve? Can you get help if you need it? Is there an opportunity for you to get paid work if you learn Express?

+ +

Based on the number of high profile companies that use Express, the number of people contributing to the codebase, and the number of people providing both free and paid for support, then yes, Express is a popular framework!

+ +

Is Express opinionated?

+ +

Web frameworks often refer to themselves as "opinionated" or "unopinionated".

+ +

Opinionated frameworks are those with opinions about the "right way" to handle any particular task. They often support rapid development in a particular domain (solving problems of a particular type) because the right way to do anything is usually well-understood and well-documented. However they can be less flexible at solving problems outside their main domain, and tend to offer fewer choices for what components and approaches they can use.

+ +

Unopinionated frameworks, by contrast, have far fewer restrictions on the best way to glue components together to achieve a goal, or even what components should be used. They make it easier for developers to use the most suitable tools to complete a particular task, albeit at the cost that you need to find those components yourself.
+
+ Express is unopinionated. You can insert almost any compatible middleware you like into the request handling chain, in almost any order you like. You can structure the app in one file or multiple files, and using any directory structure. You may sometimes feel that you have too many choices!

+ +

What does Express code look like?

+ +

In a traditional data-driven website, a web application waits for HTTP requests from the web browser (or other client). When a request is received the application works out what action is needed based on the URL pattern and possibly associated information contained in POST data or GET data. Depending on what is required it may then read or write information from a database or perform other tasks required to satisfy the request. The application will then return a response to the web browser, often dynamically creating an HTML page for the browser to display by inserting the retrieved data into placeholders in an HTML template.

+ +

Express provides methods to specify what function is called for a particular HTTP verb (GET, POST, SET, etc.) and URL pattern ("Route"), and methods to specify what template ("view") engine is used, where template files are located, and what template to use to render a response. You can use Express middleware to add support for cookies, sessions, and users, getting POST/GET parameters, etc. You can use any database mechanism supported by Node (Express does not define any database-related behaviour).

+ +

The following sections explain some of the common things you'll see when working with Express and Node code.

+ +

דוגמה Hello world

+ +

ראשית בואו נבחן דוגמה סטנדרטית של Express Hello World (בהמשך נסביר כל חלק בקוד כאן ובהמשך)

+ +
+

Tip: If you have Node and Express already installed (or if you install them as shown in the next article), you can save this code in a text file called app.js and run it in a bash command prompt by calling:   

+ +

node ./app.js

+
+ +
var express = require('express');
+var app = express();
+
+app.get('/', function(req, res) {
+  res.send('Hello World!');
+});
+
+app.listen(3000, function() {
+  console.log('Example app listening on port 3000!');
+});
+
+ +

שתי השורות הראשונות require() (מיבא) את מודול express ויוצר Express application, אובייקט זה נקרא באופן מסורתי app זה מכיל מתודות לניתוב בקשות HTTP,

+ +

 configuring middleware, rendering HTML views, registering a template engine, and modifying application settings that control how the application behaves (e.g. the environment mode, whether route definitions are case sensitive, etc.)

+ +

The middle part of the code (the three lines starting with app.get) shows a route definition. The app.get() method specifies a callback function that will be invoked whenever there is an HTTP GET request with a path ('/') relative to the site root. The callback function takes a request and a response object as arguments, and simply calls send() on the response to return the string "Hello World!"

+ +

The final block starts up the server on port '3000' and prints a log comment to the console. With the server running, you could go to localhost:3000 in your browser to see the example response returned.

+ +

ייבוא ויצירת מודלים

+ +

A module is a JavaScript library/file that you can import into other code using Node's require() function. Express itself is a module, as are the middleware and database libraries that we use in our Express applications.

+ +

The code below shows how we import a module by name, using the Express framework as an example. First we invoke the require() function, specifying the name of the module as a string ('express'), and calling the returned object to create an Express application. We can then access the properties and functions of the application object.

+ +
var express = require('express');
+var app = express();
+
+ +

You can also create your own modules that can be imported in the same way.

+ +
+

Tip: You will want to create your own modules, because this allows you to organise your code into managable parts — a monolithic single-file application is hard to understand and maintain. Using modules also helps you manage your namespace, because only the variables you explicitly export are imported when you use a module.

+
+ +

To make objects available outside of a module you just need to expose them as additional properties on the exports object. For example, the square.js module below is a file that exports area() and perimeter() methods:

+ +
exports.area = function(width) { return width * width; };
+exports.perimeter = function(width) { return 4 * width; };
+
+ +

We can import this module using require(), and then call the exported method(s) as shown:

+ +
var square = require('./square'); // Here we require() the name of the file without the (optional) .js file extension
+console.log('The area of a square with a width of 4 is ' + square.area(4));
+ +
+

Note: You can also specify an absolute path to the module (or a name, as we did initially).

+
+ +

If you want to export a complete object in one assignment instead of building it one property at a time, assign it to module.exports as shown below (you can also do this to make the root of the exports object a constructor or other function):

+ +
module.exports = {
+  area: function(width) {
+    return width * width;
+  },
+
+  perimeter: function(width) {
+    return 4 * width;
+  }
+};
+
+ +
+

Note: You can think of exports as a shortcut to module.exports within a given module. In fact, exports is just a variable that gets initialized to the value of module.exports before the module is evaluated. That value is a reference to an object (empty object in this case). This means that exports holds a reference to the same object referenced by module.exports. It also means that by assigning another value to exports it's no longer bound to module.exports.

+
+ +

For a lot more information about modules see Modules (Node API docs).

+ +

Using asynchronous APIs

+ +

JavaScript code frequently uses asynchronous rather than synchronous APIs for operations that may take some time to complete. A synchronous API is one in which each operation must complete before the next operation can start. For example, the following log functions are synchronous, and will print the text to the console in order (First, Second).

+ +
console.log('First');
+console.log('Second');
+
+ +

By contrast, an asynchronous API is one in which the API will start an operation and immediately return (before the operation is complete). Once the operation finishes, the API will use some mechanism to perform additional operations. For example, the code below will print out "Second, First" because even though setTimeout() method is called first, and returns immediately, the operation doesn't complete for several seconds.

+ +
setTimeout(function() {
+   console.log('First');
+   }, 3000);
+console.log('Second');
+
+ +

Using non-blocking asynchronous APIs is even more important on Node than in the browser because Node is a single-threaded event-driven execution environment. "Single threaded" means that all requests to the server are run on the same thread (rather than being spawned off into separate processes). This model is extremely efficient in terms of speed and server resources, but it does mean that if any of your functions call synchronous methods that take a long time to complete, they will block not just the current request, but every other request being handled by your web application.

+ +

There are a number of ways for an asynchronous API to notify your application that it has completed. The most common way is to register a callback function when you invoke the asynchronous API, that will be called back when the operation completes. This is the approach used above.

+ +
+

Tip: Using callbacks can be quite "messy" if you have a sequence of dependent asynchronous operations that must be performed in order because this results in multiple levels of nested callbacks. This problem is commonly known as "callback hell". This problem can be reduced by good coding practices (see http://callbackhell.com/), using a module like async, or even moving to ES6 features like Promises.

+
+ +
+

Note: A common convention for Node and Express is to use error-first callbacks. In this convention, the first value in your callback functions is an error value, while subsequent arguments contain success data. There is a good explanation of why this approach is useful in this blog: The Node.js Way - Understanding Error-First Callbacks (fredkschott.com).

+
+ +

Creating route handlers

+ +

In our Hello World Express example (see above), we defined a (callback) route handler function for HTTP GET requests to the site root ('/').

+ +
app.get('/', function(req, res) {
+  res.send('Hello World!');
+});
+
+ +

The callback function takes a request and a response object as arguments. In this case, the method simply calls send() on the response to return the string "Hello World!" There are a number of other response methods for ending the request/response cycle, for example, you could call res.json() to send a JSON response or res.sendFile() to send a file.

+ +
+

JavaScript tip: You can use any argument names you like in the callback functions; when the callback is invoked the first argument will always be the request and the second will always be the response. It makes sense to name them such that you can identify the object you're working with in the body of the callback.

+
+ +

The Express application object also provides methods to define route handlers for all the other HTTP verbs, which are mostly used in exactly the same way:

+ +

checkout()copy()delete()get()head()lock()merge()mkactivity(), mkcol(), move(), m-search(), notify(), options(), patch(), post(), purge(), put(), report(), search(), subscribe(), trace(), unlock(), unsubscribe().

+ +

There is a special routing method, app.all(), which will be called in response to any HTTP method. This is used for loading middleware functions at a particular path for all request methods. The following example (from the Express documentation) shows a handler that will be executed for requests to /secret irrespective of the HTTP verb used (provided it is supported by the http module).

+ +
app.all('/secret', function(req, res, next) {
+  console.log('Accessing the secret section ...');
+  next(); // pass control to the next handler
+});
+ +

Routes allow you to match particular patterns of characters in a URL, and extract some values from the URL and pass them as parameters to the route handler (as attributes of the request object passed as a parameter).

+ +

Often it is useful to group route handlers for a particular part of a site together and access them using a common route-prefix (e.g. a site with a Wiki might have all wiki-related routes in one file and have them accessed with a route prefix of /wiki/). In Express this is achieved by using the express.Router object. For example, we can create our wiki route in a module named wiki.js, and then export the Router object, as shown below:

+ +
// wiki.js - Wiki route module
+
+var express = require('express');
+var router = express.Router();
+
+// Home page route
+router.get('/', function(req, res) {
+  res.send('Wiki home page');
+});
+
+// About page route
+router.get('/about', function(req, res) {
+  res.send('About this wiki');
+});
+
+module.exports = router;
+
+ +
+

Note: Adding routes to the Router object is just like adding routes to the app object (as shown previously).

+
+ +

To use the router in our main app file we would then require() the route module (wiki.js), then call use() on the Express application to add the Router to the middleware handling path. The two routes will then be accessible from /wiki/ and /wiki/about/.

+ +
var wiki = require('./wiki.js');
+// ...
+app.use('/wiki', wiki);
+ +

We'll show you a lot more about working with routes, and in particular about using the Router, later on in the linked section Routes and controllers .

+ +

Using middleware

+ +

Middleware is used extensively in Express apps, for tasks from serving static files to error handling, to compressing HTTP responses. Whereas route functions end the HTTP request-response cycle by returning some response to the HTTP client, middleware functions typically perform some operation on the request or response and then call the next function in the "stack", which might be more middleware or a route handler. The order in which middleware is called is up to the app developer.

+ +
+

Note: The middleware can perform any operation, execute any code, make changes to the request and response object, and it can also end the request-response cycle. If it does not end the cycle then it must call next() to pass control to the next middleware function (or the request will be left hanging).

+
+ +

Most apps will use third-party middleware in order to simplify common web development tasks like working with cookies, sessions, user authentication, accessing request POST and JSON data, logging, etc. You can find a list of middleware packages maintained by the Express team (which also includes other popular 3rd party packages). Other Express packages are available on the NPM package manager.

+ +

To use third party middleware you first need to install it into your app using NPM. For example, to install the morgan HTTP request logger middleware, you'd do this:

+ +
$ npm install morgan
+
+ +

You could then call use() on the Express application object to add the middleware to the stack:

+ +
var express = require('express');
+var logger = require('morgan');
+var app = express();
+app.use(logger('dev'));
+...
+ +
+

Note: Middleware and routing functions are called in the order that they are declared. For some middleware the order is important (for example if session middleware depends on cookie middleware, then the cookie handler must be added first). It is almost always the case that middleware is called before setting routes, or your route handlers will not have access to functionality added by your middleware.

+
+ +

You can write your own middleware functions, and you are likely to have to do so (if only to create error handling code). The only difference between a middleware function and a route handler callback is that middleware functions have a third argument next, which middleware functions are expected to call if they are not that which completes the request cycle (when the middleware function is called, this contains the next function that must be called).

+ +

You can add a middleware function to the processing chain with either app.use() or app.add(), depending on whether you want to apply the middleware to all responses or to responses with a particular HTTP verb (GET, POST, etc). You specify routes the same in both cases, though the route is optional when calling app.use().

+ +

The example below shows how you can add the middleware function using both methods, and with/without a route.

+ +
var express = require('express');
+var app = express();
+
+// An example middleware function
+var a_middleware_function = function(req, res, next) {
+  // ... perform some operations
+  next(); // Call next() so Express will call the next middleware function in the chain.
+}
+
+// Function added with use() for all routes and verbs
+app.use(a_middleware_function);
+
+// Function added with use() for a specific route
+app.use('/someroute', a_middleware_function);
+
+// A middleware function added for a specific HTTP verb and route
+app.get('/', a_middleware_function);
+
+app.listen(3000);
+ +
+

JavaScript Tip: Above we declare the middleware function separately and then set it as the callback. In our previous route handler function we declared the callback function when it was used. In JavaScript, either approach is valid.

+
+ +

The Express documentation has a lot more excellent documentation about using and writing Express middleware.

+ +

Serving static files

+ +

You can use the express.static middleware to serve static files, including your images, CSS and JavaScript (static() is the only middleware function that is actually part of Express). For example, you would use the line below to serve images, CSS files, and JavaScript files from a directory named 'public' at the same level as where you call node:

+ +
app.use(express.static('public'));
+
+ +

Any files in the public directory are served by adding their filename (relative to the base "public" directory) to the base URL. So for example:

+ +
http://localhost:3000/images/dog.jpg
+http://localhost:3000/css/style.css
+http://localhost:3000/js/app.js
+http://localhost:3000/about.html
+
+ +

You can call static() multiple times to serve multiple directories. If a file cannot be found by one middleware function then it will simply be passed on to the subsequent middleware (the order that middleware is called is based on your declaration order).

+ +
app.use(express.static('public'));
+app.use(express.static('media'));
+
+ +

You can also create a virtual prefix for your static URLs, rather than having the files added to the base URL. For example, here we specify a mount path so that the files are loaded with the prefix "/media":

+ +
app.use('/media', express.static('public'));
+
+ +

Now, you can load the files that are in the public directory from the /media path prefix.

+ +
http://localhost:3000/media/images/dog.jpg
+http://localhost:3000/media/video/cat.mp4
+http://localhost:3000/media/cry.mp3
+
+ +
+

Note: See also Serving static files in Express.

+
+ +

Handling errors

+ +

Errors are handled by one or more special middleware functions that have four arguments, instead of the usual three: (err, req, res, next). For example:

+ +
app.use(function(err, req, res, next) {
+  console.error(err.stack);
+  res.status(500).send('Something broke!');
+});
+
+ +

These can return any content required, but must be called after all other app.use() and routes calls so that they are the last middleware in the request handling process!

+ +

Express comes with a built-in error handler, which takes care of any remaining errors that might be encountered in the app. This default error-handling middleware function is added at the end of the middleware function stack. If you pass an error to next() and you do not handle it in an error handler, it will be handled by the built-in error handler; the error will be written to the client with the stack trace.

+ +
+

Note: The stack trace is not included in the production environment. To run it in production mode you need to set the environment variable NODE_ENV to 'production'.

+
+ +
+

Note: HTTP404 and other "error" status codes are not treated as errors. If you want to handle these, you can add a middleware function to do so. For more information see the FAQ.

+
+ +

For more information see Error handling (Express docs).

+ +

Using databases

+ +

Express apps can use any database mechanism supported by Node (Express itself doesn't define any specific additional behaviour/requirements for database management). There are many options, including PostgreSQL, MySQL, Redis, SQLite, MongoDB, etc.

+ +

In order to use these you have to first install the database driver using NPM. For example, to install the driver for the popular NoSQL MongoDB you would use the command:

+ +
$ npm install mongodb
+
+ +

The database itself can be installed locally or on a cloud server. In your Express code you require the driver, connect to the database, and then perform create, read, update, and delete (CRUD) operations. The example below (from the Express documentation) shows how you can find "mammal" records using MongoDB.

+ +
//this works with older versions of  mongodb version ~ 2.2.33
+var MongoClient = require('mongodb').MongoClient;
+
+MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
+  if (err) throw err;
+
+  db.collection('mammals').find().toArray(function (err, result) {
+    if (err) throw err;
+
+    console.log(result);
+  });
+});
+
+
+//for mongodb version 3.0 and up
+let MongoClient = require('mongodb').MongoClient;
+MongoClient.connect('mongodb://localhost:27017/animals', function(err, client){
+   if(err) throw err;
+
+   let db = client.db('animals');
+   db.collection('mammals').find().toArray(function(err, result){
+     if(err) throw err;
+     console.log(result);
+     client.close();
+   });
+});
+
+ +

Another popular approach is to access your database indirectly, via an Object Relational Mapper ("ORM"). In this approach you define your data as "objects" or "models" and the ORM maps these through to the underlying database format. This approach has the benefit that as a developer you can continue to think in terms of JavaScript objects rather than database semantics, and that there is an obvious place to perform validation and checking of incoming data. We'll talk more about databases in a later article.

+ +

For more information see Database integration (Express docs).

+ +

Rendering data (views)

+ +

Template engines (referred to as "view engines" by Express) allow you to specify the structure of an output document in a template, using placeholders for data that will be filled in when a page is generated. Templates are often used to create HTML, but can also create other types of documents. Express has support for a number of template engines, and there is a useful comparison of the more popular engines here: Comparing JavaScript Templating Engines: Jade, Mustache, Dust and More.

+ +

In your application settings code you set the template engine to use and the location where Express should look for templates using the 'views' and 'view engines' settings, as shown below (you will also have to install the package containing your template library too!)

+ +
const express = require('express');
+const path = require('path');
+const app = express();
+
+// Set directory to contain the templates ('views')
+app.set('views', path.join(__dirname, 'views'));
+
+// Set view engine to use, in this case 'some_template_engine_name'
+app.set('view engine', 'some_template_engine_name');
+
+ +

The appearance of the template will depend on what engine you use. Assuming that you have a template file named "index.<template_extension>" that contains placeholders for data variables named 'title' and "message", you would call Response.render() in a route handler function to create and send the HTML response:

+ +
app.get('/', function(req, res) {
+  res.render('index', { title: 'About dogs', message: 'Dogs rock!' });
+});
+ +

For more information see Using template engines with Express (Express docs).

+ +

File structure

+ +

Express makes no assumptions in terms of structure or what components you use. Routes, views, static files, and other application-specific logic can live in any number of files with any directory structure. While it is perfectly possible to have the whole Express application in one file, typically it makes sense to split your application into files based on function (e.g. account management, blogs, discussion boards) and architectural problem domain (e.g. model, view or controller if you happen to be using an MVC architecture).

+ +

In a later topic we'll use the Express Application Generator, which creates a modular app skeleton that we can easily extend for creating web applications.

+ + + +

Summary

+ +

Congratulations, you've completed the first step in your Express/Node journey! You should now understand Express and Node's main benefits, and roughly what the main parts of an Express app might look like (routes, middleware, error handling, and template code). You should also understand that with Express being an unopinionated framework, the way you pull these parts together and the libraries that you use are largely up to you!

+ +

Of course Express is deliberately a very lightweight web application framework, so much of its benefit and potential comes from third party libraries and features. We'll look at those in more detail in the following articles. In our next article we're going to look at setting up a Node development environment, so that you can start seeing some Express code in action.

+ +

See also

+ + + +
{{NextMenu("Learn/Server-side/Express_Nodejs/development_environment", "Learn/Server-side/Express_Nodejs")}}
+ +

In this module

+ + diff --git a/files/he/learn/server-side/index.html b/files/he/learn/server-side/index.html new file mode 100644 index 0000000000..9816a95427 --- /dev/null +++ b/files/he/learn/server-side/index.html @@ -0,0 +1,50 @@ +--- +title: תכנות אתרים בצד שרת +slug: Learn/Server-side +translation_of: Learn/Server-side +--- +
ת{{LearnSidebar}}
+ +

The Dynamic Websites  Server-side programming topic is a series of modules that show how to create dynamic websites; websites that deliver customised information in response to HTTP requests. The modules provide a general introduction to server-side programming, along with specific beginner-level guides on how to use the Django (Python) and Express (Node.js/JavaScript) web frameworks to create basic applications.

+ +

Most major websites use some kind of server-side technology to dynamically display data as required. For example, imagine how many products are available on Amazon, and imagine how many posts have been written on Facebook. Displaying all of these using different static pages would be extremely inefficient, so instead such sites display static templates (built using HTML, CSS, and JavaScript), and then dynamically update the data displayed inside those templates when needed, such as when you want to view a different product on Amazon.

+ +

In the modern world of web development, learning about server-side development is highly recommended.

+ +

מסלול למידה

+ +

תחילת הדרך עם תכנות בצד שרת זה בדרך כלל קל יותר מאשר תכנות בצד לקוח. בגלל שאתרים דינמיים לרוב מבצעים הרבה פעולות דומות מאוד (אחזור מידע ממסד נתונים והצגתם בעמוד, אימות נתונים שהוזנו ע"י משתמש ושמירתם במסד נתונים, בדיקת הרשאות משתמש וכניסת משתמש וכו') ונבנים באמצעות מסגרות אינטרנט (frameworks) המקלות על פעולות אלה ושאר שרתי האינטרנט הנפוצים.

+ +

Basic knowledge of programming concepts (or of a particular programming language) is useful, but not essential. Similarly, expertise in client-side coding is not required, but a basic knowledge will help you work better with the developers creating your client-side web "front end".

+ +

תצטרך להבין "כיצד הרשת עובדת". אנו ממליצים שקודם תקרא את הנושאים הבאים: 

+ + + +

With that basic understanding, you'll be ready to work your way through the modules in this section. 

+ +

מודולים

+ +

This topic contains the following modules. You should start with the first module, then go on to one of the following modules, which show how to work with two very popular server-side languages using appropriate web frameworks. 

+ +
+
Server-side website programming first steps
+
This module provides technology-agnostic information about server-side website programming such as "what is it?", "how does it differ from client-side programming?", and "why is it useful?". This module also outlines some of the more popular server-side web frameworks and gives guidance on how to select the best one for your site. Lastly, an introduction to web server security is provided.
+
Django Web Framework (Python)
+
Django is an extremely popular and fully featured server-side web framework, written in Python. The module explains why Django is such a good web server framework, how to set up a development environment and how to perform common tasks with it.
+
Express Web Framework (Node.js/JavaScript)
+
Express is a popular web framework, written in JavaScript and hosted within the node.js runtime environment. The module explains some of the key benefits of this framework, how to set up your development environment and how to perform common web development and deployment tasks.
+
+ +

ראה עוד

+ +
+
Node server without framework
+
This article provides a simple static file server built with pure Node.js, for those of you not wanting to use a framework.
+
Properly configuring server MIME types
+
Configuring your server to send the correct {{Glossary("MIME types")}} (also known as media types or content types) to browsers is important for browsers to be able to properly process and display the content. It is also important to prevent malicious content from masquerading as benign content.
+
diff --git a/files/he/mdn/community/index.html b/files/he/mdn/community/index.html new file mode 100644 index 0000000000..dce5bcd87b --- /dev/null +++ b/files/he/mdn/community/index.html @@ -0,0 +1,53 @@ +--- +title: הצטרפות לקהילת מסמכי הרשת של MDN +slug: MDN/Community +tags: + - מדריך + - נחיתה + - קהילה +translation_of: MDN/Community +--- +
{{MDNSidebar}}
+ +
{{IncludeSubnav("/he/docs/MDN")}}
+ +
+

אתר מסמכי הרשת של MDN הוא יותר מסתם ויקי: זוהי קהילה של מפתחים שעובדים יחד לעשות את MDN משאב מדהים למפתחי ווב.

+
+ +

נשמח אם תתרום ל- MDN, אבל נשמח יותר אם תשתתף בקהילת MDN. הנה שלושה צעדים פשוטים להתחבר:

+ +
    +
  1. ליצור חשבון MDN.
  2. +
  3. להשתתף בדיונים.
  4. +
  5. לעקוב אחרי מה שקורה.
  6. +
+ +

איך עובדת הקהילה

+ +

להלן מאמרים נוספים שמתארים את קהילת MDN.

+ +
+
+
+
תפקידים בקהילה
+
קיימים מספר תפקידים בקהילת MDN, שהם בעלי אחריות מסוימת.
+
ספרינטים לתיעוד (Doc Sprint)
+
זהו מדריך לארגון ספרינט תיעוד. הוא כולל עצות וטיפים מאנשים שארגנו ספרינטים של תיעוד, כדי לעזור לך לארגן אחד כזה.
+
עקוב אחרי מה שקורה
+
MDN מובא לך על-ידי קהילת רשת המפתחים של מוזילה. הנה כמה דרכים בהן אנחנו משתפים מידע לגבי העבודה שלנו.
+
+ +
+
+
+ +
+
+
שיחות קהילה ב- MDN
+
ה"עבודה" של MDN קורה באתר של MDN, אך ה"קהילה" גם קורה בדיונים (אסכינכרוניים) וצ'אטים ופגישות מקוונים (סיכנרוניים).
+
עבודה בקהילה
+
חלק גדול בתרומה לתיעוד ב- MDN בכל היקף הוא לדעת כיצד לעבוד כחלק מקהילת MDN. מאמר זה מציע טיפים שיעזרו לך להפיק את המירב מהאינטראקציות שלך עם הן עם כותבים והם עם צוותי פיתוח אחרים.
+
+
+
diff --git a/files/he/mdn/contribute/getting_started/index.html b/files/he/mdn/contribute/getting_started/index.html new file mode 100644 index 0000000000..4dd16bb2f1 --- /dev/null +++ b/files/he/mdn/contribute/getting_started/index.html @@ -0,0 +1,131 @@ +--- +title: יוצאים לדרך עם MDN +slug: MDN/Contribute/Getting_started +tags: + - למתחילים + - מבוא + - מדריך +translation_of: MDN/Contribute/Getting_started +--- +
{{MDNSidebar}}
+ +

אנחנו קהילה פתוחה של מפתחים הבונים מקורות לאינטרנט טוב יותר, בלי חשיבות למותג, דפדפן, או פלטפורמה. כל אחד יכול לתרום וכל אדם הבוחר לעשות זאת מחזק אותנו. יחד אנחנו יכולים להמשיך לתמוך בחדשנות באינטרנט לשרת את טובת הכלל. זה מתחיל כאן, זה מתחיל אתך.

+ +

כל חלק ב-MDN (החל מהקוד שמפעיל את האתר הזה ועד לתיעוד, הדוגמאות וההדגמות) נוצר על ידי קהילה של מפתחים וכותבים. לכל אחד יש מה להציע, ואנחנו מקווים שתצטרף אלינו!

+ +

3 שלבים פשוטים אל MDN

+ +

MDN היא ויקי בה כל אחד יכול להוסיף ולערוך תוכן. אתה לא צריך להיות מתכנת או לדעת הרבה על טכנולוגיות. ישנם הרבה דברים שניתן לעשות, החל מהפשוטים (הגהה ותיקון טעויות הקלדה) ועד למורכבים (כתיבת תיעוד API).

+ +

התרומה היא פשוטה ובטוחה. אפילו אם אתה עושה טעות, ניתן לתקן אותה בקלות; אם אינך יודע איך בדיוק דברים צריכים להראות, או שהדקדוק שלך אינו כל-כך נהדר, אל תדאג! יש לנו צוות של אנשים שהתפקיד שלהם הוא להבטיח שהתכנים של MDN הם טובים ככל הניתן. יהיה מישהו שיבדוק שהעבודה שלך נקייה וכתובה היטב. שתף את מה שאתה יודע ודע את החזקות שלך, ובטח ששאר הקהילה תעזור להפוך את העבודה שלך להיות טובה אף יותר.

+ +

צעד 1: צור חשבון ב-MDN

+ +

כדי להתחיל לתרום ל-MDN, תחילה יש ליצור חשבון ב-MDN, לפרטים ראה איך ליצור חשבון.

+ +

צעד 2: בחר מטלה להשלים

+ +

עכשיו כשאתה מחובר, קרא את התיאורים של סוגי המטלות השונים ב{{anch("סוגי מטלות אפשריות", "רשימה מטה")}}, והחלט מה מהם מתאים לך. אתה יכול לבחור כל מטלה שתרצה ולהתחיל את התרומה שלך.

+ +

צעד 3: בצע את המטלה

+ +

ברגע שהחלטת איזה סוג מטלה אתה רוצה לעשות, בחר עמוד ספציפי, דוגמת קוד וכו' לעבוד עליו, ופשוט עשה זאת!

+ +

אל תדאג לגבי השלמת המשימה באופן מושלם; מתנדבי MDN אחרים כאן כדי לעזור לך לתקן טעויות שהשתרבבו פנימה. אם יש לך שאלות בעיצומה של מטלה, ראה את דף הקהילה למידע על רשימות תפוצה וערוצי צ'אט בהם תוכל לקבל תשובות.

+ +
+

הערה: אם אתה רוצה להתנסות עם עריכה ב-MDN לפני שאתה עושה משהו "על אמת", יש לנו עמוד  ארגז-חול בו ניתן לשחק. אנא הגבל את התנסויותך לעמוד זה. אנא אל תעשה שינויים לא-הכרחיים לעמודי תוכן רק כדי לראות מה קורה; זה רק יגרום לבלאגן שאחרים יצטרכו לנקות אחריך.

+
+ +

כאשר סיימת עם המטלה שבחרת, הרגש חופשי לבחור דבר אחר, או ראה מטה דברים אחרים שאתה יכול לעשות ב-MDN.

+ +

סוגי מטלות אפשריות

+ +

ישנם דרכים רבות בהן תוכל לתרום ל-MDN, בהתאם לכישורים ולתחומי העניין שלך. אפילו שחלק מהמשימות עלולות להרתיע, יש לנו גם הרבה פעולות פשוטות זמינות. רבות מהן מצריכות רק חמש דקות (או פחות!) מזמנך. ביחד עם המטלות ותיאורן הקצר, תמצא את פרק הזמן המוערך שכל מטלה בדרך-כלל לוקחת.

+ +

אפשרות 1: אני אוהב מילים

+ +

אתה יכול לעזור לנו לסקור או לערוך מסמכים קיימים, ולהצמיד תיוגים מתאימים עבורם.

+ + + +
הערה: אם אתה מסקר מאמרים או כותב מאמרים חדשים, אנו מבקשים שתעבור קודם כל על מדריך הסגנון. זה יעזור להבטיח שהמאמרים עקביים.
+ +

אפשרות 2: אני אוהב קוד

+ +

אנחנו זקוקים לעוד דוגמאות קוד! אתה גם יכול לעזור לבנות את פלטפורמת האתר שלנו, כומא!

+ + + +

אפשרות 3: אני אוהב גם מילים וגם קוד

+ +

יש לנו מטלות שדורשות גם כישורים טכניים וגם כישורי שפה, כמו כתיבת מאמרים חדשים, סיקור דיוק טכני, או התאמת מסמכים.

+ + + +

אפשרות 4: אני רוצה את MDN בשפה שלי

+ +

כל עבודות הלוקליזציה והתרגום שנעשו ב- MDN, נעשו על ידי הקהילת המתנדבים המדהימה שלנו.

+ + + +

אפשרות 5: מצאתי מידע שגוי אבל אני לא יודע כיצד לתקנו

+ +

אתה יכול לדווח על בעיות על ידי דיווח על באג בתיעוד. (5 דקות)

+ +

השתמש בערכי השדות הללו:

+ + + + + + + + + + + + + + + + + + + + + + + + +
שדה באגזילהערך
מוצרתיעוד מפתח
מרכיב[בחר איזור מתאים לנושא, או "כללי" אם אתה לא בטוח או אתה לא מוצא אחד מתאים]
URLהעמוד בו מצאת את הבעיה
תיאורככל שאתה יודע או שיש לך זמן לתאר אודות הבעיה והמקום למצוא את המידע הנכון. זה עשוי לכלול אנשים ("דבר עם פלוני ועם אלמוני") כמו גם קישורים לאתרים.
+ +

דברים אחרים שאתה יכול לעשות ב- MDN

+ + diff --git a/files/he/mdn/contribute/howto/create_an_mdn_account/index.html b/files/he/mdn/contribute/howto/create_an_mdn_account/index.html new file mode 100644 index 0000000000..926b8e8d02 --- /dev/null +++ b/files/he/mdn/contribute/howto/create_an_mdn_account/index.html @@ -0,0 +1,42 @@ +--- +title: איך ליצור חשבון MDN +slug: MDN/Contribute/Howto/Create_an_MDN_account +tags: + - למתחילים + - מדריך + - תיעוד +translation_of: MDN/Contribute/Howto/Create_an_MDN_account +--- +
{{MDNSidebar}}
+ +

כדי לערוך תוכן ב- MDN, עליך ליצור פרופיל MDN. אין צורך ליצור פרופיל אם ברצונך רק לקרוא ולעיין במסמכי MDN. מדריך זה יעזור לך להגדיר את פרופיל ה- MDN.

+ +
+
למה MDN זקוקים לכתובת הדוא"ל שלי?
+
+כתובת הדוא"ל שלך משמשת לשחזור החשבון, ובמידת הצורך ליצירת קשר על-ידי מנהלי MDN לגבי החשבון שלך או פעילותך באתר.
+
+בנוסף, תוכל להירשם להתראות (כמו כשעמודים מסוימים משתנים) והודעות (למשל, אם תבחר להצטרף לצוות בדיקות הבטא שלנו, תוכל לקבל הודעות לגבי שינויים המצריכים בדיקה).
+
+כתובת הדוא"ל שלך לעולם לא תוצג ב- MDN ותשמש רק בהתאם למדיניות הפרטיות שלנו.
+ +
אם נכנסת ל- MDN באמצעות GitHub, והשתמשת בכתובת דוא"ל אוטומטית (ללא מענה) ב- GitHub, לא תקבל הודעות מ- MDN (כולל התראות כשתירשם לעמודים).
+
+
+ +
    +
  1. בראש כל עמוד ב- MDN ניתן למצוא את לחצן Sign in. מקם עליו את סמן העכבר (או הקש עליו, אם אתה משתמש במכשיר נייד) כדי להציג רשימה של שירותי האימות הנתמכים בכניסה ל- MDN.
  2. +
  3. בחר בשירות הרצוי לצורך כניסה. כרגע, רק GitHub זמין. שים לב שאם בחרת ב- GitHub, יופיע קישור לפרופיל ה- GitHub שלך בעמוד הפרופיל הציבורי שלך ב- MDN.
  4. +
  5. מלא את בקשות GitHub כדי לקשר את חשבון ה- MDN שלך.
  6. +
  7. לאחר ששירות האימות יחזיר אותך ל- MDN, תתבקש להזין שם משתמש וכתובת דוא"ל. שם המשתמש שלך יוצג באופן ציבורי כדי לתת קרדיט לעבודה שעשית. אל תשתמש בכתובת הדוא"ל שלך כשם המשתמש שלך.
  8. +
  9. הקלק על Create my MDN profile.
  10. +
  11. אם כתובת הדוא"ל שציינת בצעד 4 אינו זהה לזה של שירות האימות, אנא בדוק את תיבת הדוא"ל שלך והקלק על הקישור בהודעת האישור ששלחנו אליך.
  12. +
+ +

זה הכל! יש לך חשבון MDN, ואתה יכול לערוך עמודים כבר עכשיו!

+ +

אתה יכול להקליק על השם שלך בראש כל עמוד MDN ולראות את הפרופיל הציבורי שלך. משם תוכל להקליק על Edit כדי לערוך שינויים או תוספות לפרופיל שלך.

+ +
+

שמות משתמש חדשים לא יכולים להכיל רווחים או "@". יש לזכור ששם המשתמש שלך יוצג באופן ציבורי כדי לזהות את העבודה שעשית.

+
diff --git a/files/he/mdn/contribute/howto/index.html b/files/he/mdn/contribute/howto/index.html new file mode 100644 index 0000000000..2d2e665e4f --- /dev/null +++ b/files/he/mdn/contribute/howto/index.html @@ -0,0 +1,18 @@ +--- +title: 'MDN web docs: How-to guides' +slug: MDN/Contribute/Howto +tags: + - Documentation + - Guide + - Howto + - Landing + - MDN Meta + - NeedsTranslation + - TopicStub +translation_of: MDN/Contribute/Howto +--- +
{{MDNSidebar}}{{IncludeSubnav("/en-US/docs/MDN")}}
+ +

These articles provide step-by-step guides to accomplishing specific goals when contributing to MDN.

+ +

{{LandingPageListSubpages}}

diff --git a/files/he/mdn/contribute/index.html b/files/he/mdn/contribute/index.html new file mode 100644 index 0000000000..283b36785b --- /dev/null +++ b/files/he/mdn/contribute/index.html @@ -0,0 +1,66 @@ +--- +title: תורמים לMDN +slug: MDN/Contribute +translation_of: MDN/Contribute +--- +
{{MDNSidebar}}
+ +

ברוך הבא! העצם ביקורך בעמוד זה, לקחת את הצעד הראשון לעבר הפיכה למתנדב MDN. המדריכים הרשומים כאן מכסים את כל היבטי ההתנדבות בMDN, כולל מדריכי סגנון, מדריכים לשימוש העורך וכליו, ועוד. בבקשה ודא שקראת (ושאתה מקיים את) תנאי מוזילה לפני שאתה עורך או מוסיף עמודים חדשים.

+ +
+
+

מדריכים למתנדב

+ +
+
מתחילים
+
מדריך מהיר להתחיל ולעשות את התרומה הראשונה שלך.
+
מדריך תוכן וסגנון
+
מדריך MDN לתוכן ולסגנון מספק פרטים אודות סגנון כתיבה, פריסת עמוד, וסגנונות תוכן, כך שהתוכן שאתה כותב יתאים לשאר התוכן של MDN.
+
מדריך עורך
+
מדריך שלם לשימוש בעורך של MDN.
+
סיקור מאמרים
+
מדריך לביצוע סיקור עריכתי וטכני של תוכן מאמרים, לעזור לנו להבטיח שכל התוכן בMDN הוא שימושי וקריא ככל הניתן.
+
טרמינולוגיה וקונבנציות
+
מדריכי הטרמינולוגיה והקונבנציות שלנו מספקים מידע שאתה יכול להשתמש כדי להבטיח שאתה משתמש בטרמינולוגיה הנכונה כאשר אתה מתאר דברים.
+
עבודה עם קהילת MDN
+
מדריך לעבודה עם הקהילה שלנו, מציאת עזרה, ותקשורת עם האנשים עם התשובות לשאלות שעולות כאשר אתה מתנדב בMDN.
+
תשובות לשאלות נפוצות
+
טיפים ותשובות לשאלות הכי שכיחות אודות התרומה לMDN.
+
+ +
+
תרומה לכומא
+
מדריך לתרומה לפרויקט כומא. כומא הוא הפלטפורמה המפעילה את האתר של MDN.
+
+
+ +
+

איך ל...

+ +

מדריכי ה'איך-ל' שלנו מספקים הוראות צעד-אחר-צעד לעזור לך להשלים מטלות ספציפיות בתרומה לMDN.

+ +
+
איך לתעד תכונת CSS
+
מדריך לכתיבת תיעוד של תכונות CSS. כל תיעוד תכונת CSS צריכה להתאים לסגנון ולפריסה המתוארת במאמר.
+
איך לתעד אלמנט HTML
+
המדריך הזה לתיעוד אלמנטי HTML יבטיח שהמסמכים שאתה כותב יתאימו לאחרים בMDN.
+
איך לתייג עמודים כמו שצריך
+
המדריך לתיוג עמודים מספק מידע אודות הסטנדרטים שלנו לתיוג, כולל רשימות של תיוגים בעלי משמעות סטנדרטית בMDN. מעקב אחר מדריך זה יבטיח שהתוכן שלך מקוטלג כמו שצריך, שניתן לחפש בו בקלות יתרה, ושמנגנון מסנני החיפוש שלנו עובדים כמו שצריך עם המאמרים שלך.
+
איך לפרש ספסיפיקציות
+
מדריך זה יעזור לך לפרש כמו שצריך ספסיפיקציות אינטרנט סטנדרטיות כמו שצריך; להיות מסוגל לקרוא כאלו יכול לההפך למלאכת אומנות, ולדעת איך לעשות את זה יעזור לך להפיק תיעוד טוב יותר.
+
+ +

לוקליזציה

+ +
+
סיור לוקליזציה מודרך
+
סיור מודרך זה ילמד אותך לעשות לוקליזציה של תוכן בMDN.
+
מדריך לוקליזציה
+
מדריך זה יספק לך נתוניםאודות תהליך הלוקליזציה של תוכן MDN.
+
פרויקטי לוקליזציה
+
מצא את פרויקט הלוקליזציה של השפה שלך—או אם אין כזה, למד איך ליצור אחד חדש!
+
+
+
+ +

 

diff --git a/files/he/mdn/contribute/localize/index.html b/files/he/mdn/contribute/localize/index.html new file mode 100644 index 0000000000..eecbc8b7e3 --- /dev/null +++ b/files/he/mdn/contribute/localize/index.html @@ -0,0 +1,61 @@ +--- +title: Localizing MDN +slug: MDN/Contribute/Localize +tags: + - Landing + - Localization + - MDN Meta + - NeedsTranslation + - TopicStub + - l10n +translation_of: MDN/Contribute/Localize +--- +
{{MDNSidebar}}
{{IncludeSubnav("/en-US/docs/MDN")}}
+ +

MDN is used by people all over the world as a reference and guide to Web technologies, as well as to the internals of Firefox itself. Our localization communities are a key part of the Mozilla project; their work in translating and localizing our documentation helps people around the world develop for the open Web. If you'd like to learn more about localization, or even start a new localization, this is the place to begin.

+ +

Types of localization on MDN

+ +

Localization on MDN comprises three aspects, which require different systems or access privileges.

+ +
+
MDN site user interface
+
The strings that appear on every MDN page (or most pages) to frame the main article content and provide navigation and user controls. These strings are translated using Mozilla’s Pontoon system, in the MDN project. If your locale is not available for MDN, a administrator must enable it. See Starting a new MDN localization.
+
MDN content
+
The main body of MDN pages, consisting of reference, guide, or tutorial articles. Articles can be translated using the built-in translation interface of MDN. If your locale is not available in the list of locales to translate into, see Starting a new MDN localization.
+
+ +
+
Macro strings
+
These strings are output by macro templates that construct certain kinds of navigation, messages, or generated structures. Because templates can have pervasive and potentially destructive effects, changes go through a pull request and review process.
+
+ +

The following pages provide more details about localizing on MDN:

+ +

{{LandingPageListSubpages}}

+ +

Localization communities on MDN

+ +

Localization activities on MDN are done both by individuals acting independently, and by groups working together, possibly as part of a larger Mozilla localization community. Localization projects on MDN are led by Localization drivers.

+ + + +

Localization tools

+ +

There are several useful tools that you'll use during localization work:

+ +
+
Pontoon
+
Used for translation of strings across multiple Mozilla projects, including the MDN user interface (as well as the Firefox user interface).
+
Transvision
+
A utility provided by the French Mozilla community, which lets you search for occurrences of an English string, finding all the various translations into a target locale that are used throughout Mozilla code. Useful for finding the preferred translations for words or phrases.
+
+ +

See also

+ + diff --git a/files/he/mdn/contribute/localize/translating_pages/index.html b/files/he/mdn/contribute/localize/translating_pages/index.html new file mode 100644 index 0000000000..3286b1cc4c --- /dev/null +++ b/files/he/mdn/contribute/localize/translating_pages/index.html @@ -0,0 +1,73 @@ +--- +title: MDN תרגום דפים באתר +slug: MDN/Contribute/Localize/Translating_pages +translation_of: MDN/Contribute/Localize/Translating_pages +--- +
{{MDNSidebar}}
+ +

מאמר זה כולל בתוכו מדריך בסיסי לתרגום תוכן באתר MDN, הכולל הסבר על מנגנון מלאכת התרגום ועצות מועילות בנוגע לדרך הנכונה לטיפול בסוגי תוכן שונים. השימוש התרגום לעברית בוצע בגוף רבים מטעמי נוחות-  אך פונה אל כלל המגדרים.

+ +

חלק מהתווים והמלל עלולים שלא להיות מיושרים ו\או מעוצבים בצורה אחידה לחלוטין, בשל מגבלות טכניות בעורך הטקסט של האתר, לשפות הנכתבות מימין לשמאל, עמכם הסליחה עד לתיקון הבדלים עיצוביים אלו.

+ +

+ +
+
+

התחלת תרגום של עמוד חדש

+
+
+ +

 כאשר תתקלו בעמוד אותו תרצו לתרגם לשפה שלכם, בצעו את הצעדים הבאים:

+ +

1. אם אתם במצב "קריאה בלבד" (read-only MDN site  ) בדפדפן ,עליכם לעבור לאתר הוויקי (wiki site)  ע"י הקלקה על הכפתור "ערוך בוויקי" (Edit in wiki).  

+ +

2. לחצו על תפריט השפות, ובחרו באפשרות הוסף תרגום (בתחתית התפריט), ועמוד בחירת השפות יופיע מייד.

+ +

3. לחץ על השפה אליה תרצו לתרגם את העמוד הנוכחי. ייפתח מייד חלון של תרגום-מאמר עם המלל המקורי שיוצג בצד שמאל של החלון.

+ +

4. תחת הכותרת תיאור התרגום, תוכלו לתרגם את הכותרת וכן ניתן  לבחירתכם לתרגם את התיוג המיוחד (SLUG) לשפה הרצויה. התיוג הזה מהווה את סיומת כתובת ה-URL לאותו העמוד (למשל "Translating_pages" לעמוד הנוכחי). חלק מהקהילות המתרגמות  נוהגות שלא לתרגם את החלק הזה לשפתן על מנת להשאירו בשפה האנגלית מטעמי נוחות. מומלץ לבדוק דפים אחרים שתורגמו כבר לשפתכם על מנת שתכירו את הנוהג המקובל בקהילת המתרגמים שלכם. תוכלו ללחוץ על סימן המינוס בסמוך לתיאור התרגום בכדי להסתיר את המידע המוצג שם לאחר שסיימתם, על מנת להגדיל את השטח המוקצה לחלונית תוכן התרגום.

+ +

5. תחת הכותרת תוכן התרגום, תוכלו להכניס את גוף התרגום שלכם לעמוד הנוכחי.

+ +

6. צרו לפחות תגית מזהה  אחת לעמוד שתרגמתם.

+ +

7. לחצו על שמור שינויים בסיום העבודה.

+ +
+

הערה: כלל האפשרויות בממשק-המשתמש במדריך לתרגום דפים, מוצגים בתחילה בשפה האנגלית. בביקורים הבאים שלכם לצורך תרגום דף מסויים, ממשק המשתמש יופיע בשפה שלכם אם היא זמינה ומותאמת מקומית באתר MDN. תרגום והתאמה מקומית של ממשק-המשתמש לשפתכם אפשרי באמצעות שימוש בכלי Pontoon. ראו פרטים נוספים על שימוש בכלי הזה בקישור Localizing with Pontoon.

+
+ +

+ +
+
עריכה של דף מתורגם
+
+ + + +

במידה והגרסה בשפה האנגלית עברה שינויים מאז העדכון האחרון של התרגום בשפה בעברית, חלונית תרגום-הדף תציג מבט של השינויים שבוצעו ("diff") בגרסה המקורית באנגלית מאז. האפשרות הזו תסייע לכם בקבלת מבט מהיר על העדכונים הדורשים תרגום.

+ +
+
תיוג של תרגומים
+
חשוב מאוד לתייג כל עמוד בתגית אחת לפחות, גם אם מדובר בתרגום. בדרך כלל מקובל לעשות שימוש באותן התגיות של המאמר המקורי באנגלית - לצורך נוחות ופשטות.
+
+ +
+

הערה למתרגמים: אין לתרגם תגיות המופיעה ברשימה הנ"ל How to properly tag pages . התגיות הללו משמשות לפעילות התקינה של מסננים שונים, וכן למטרות אחרות כגון: ניהול האתר וכן עיבוד נתונים אוטומטי, כך שתרגום שלהם\שינוי בהם עלול לפגוע בתהליכים אלו.

+
+ +

באפשרותכם ליצור תגיות חדשות לתכנים קבוצתיים, במידה ואין התייחסות אליהם בתגיות הקיימות כבר באתר.

+ +

הצעות לתורמים חדשים

+ +

אם אתם חדשים בתרגום והתאמה באתר MDN, צרפנו מספר הצעות שיסייעו:

+ +

מאמרים באוסף המונחיםGlossary  יכולים לסייע מאוד למתרגמים חדשים, מאחר והם קצרים ופשוטים 

+ +

מאמרים המתוייגים כ- tagged "l10n:priority" - הנם בעדיפות גבוהה לתרגום. בנוסף, מדריכים ומאמרים רעיוניים\מושגיים תמיד יהיו בעדיפות גבוהה יותר מדפים מידע כלליים, מאחר והקוראים נזקקים לתרגום זה בעת לימוד של מושגים חדשים.

+ +

במידה ותתקלו במלל מוקף בשני זוגות של סוגריים-מסולסלים כגון < \{{some-text("more text")}}>- השאירו אותם ללא תרגום ואל תשנו את תוי הניקוד. זהו מאקרו macro, המעניק מבנה מסויים לעמוד או מבצע פעולה חיונית אחרת. ייתכן ותפגשו אף מלל לא מתורגם הנוצר ע"י המאקרו, אך אל דאגה - אתם תלמדו יותר על ככל  שתצברו ניסיון באתר MDN (שינוי המלל מצריך הרשאות מיוחדות <special privileges> מאחר ומאקרו הן פקודות עוצמתיות). אם אתם עדיין סקרנים - הכנסו לקישור -Commonly-used macros- לצפות בפעולות נפוצות המבוצעות על ידי פקודות המאקרו.

+ +

בדקו את הקישור הבא <Localization projects page> על מנת לגלות עוד פרטים בנוגע להתאמה מקומית של האתר.

diff --git a/files/he/mdn/index.html b/files/he/mdn/index.html new file mode 100644 index 0000000000..44c51fa647 --- /dev/null +++ b/files/he/mdn/index.html @@ -0,0 +1,18 @@ +--- +title: פרויקט MDN +slug: MDN +translation_of: MDN +--- +
{{MDNSidebar}}
+ +
+

 רשת הפיתוח של מוזילה (MDN) היא ויקי בה אנו מתעדים את האינטרנט החופשי, טכנולוגיות מוזילה, Firefox OS ונושאי פיתוח אחרים. כל אחד מוזמן להוסיף ולערוך תוכן. אתה לא צריך להיות מתכנת או לדעת הרבה על טכנולוגיה; ישנם הרבה משימות שונות שצריכות להתבצע, החל מהפשוטות (הגהה ותיקון טעויות הקלדה) ועד המורכבות (כתיבת תיעוד API).

+ +
+

המטרה של פרויקט MDN היא לתעד את האינטרנט החופשי, טכנולוגיות מוזילה, ופרויקטי מוזילה. אנו מזמינים אתכם לעזור!

+
+ +

אנו זקוקים לעזרתך! זה קל. אל תדאג לגבי בקשת רשות או לגבי עשיית טעויות. מצד שני, בבקשה למד להכיר את קהילת MDN; אנחנו כאן כדי לעזור! התיעוד שמטה אמור לעזור לך להתחיל, אבל אל תהסס להצטרף לדיון ב{{IRCLink("mdn")}}, ערוץ הIRC שלנו.

+ +

+
diff --git a/files/he/mozilla/add-ons/index.html b/files/he/mozilla/add-ons/index.html new file mode 100644 index 0000000000..ca718d6324 --- /dev/null +++ b/files/he/mozilla/add-ons/index.html @@ -0,0 +1,104 @@ +--- +title: Add-ons +slug: Mozilla/Add-ons +tags: + - Add-ons + - Extension + - Extensions + - Landing + - Mozilla + - NeedsTranslation + - TopicStub +translation_of: Mozilla/Add-ons +--- +

Add-ons allow developers to extend and modify the functionality of Firefox. They are written using standard Web technologies - JavaScript, HTML, and CSS - plus some dedicated JavaScript APIs.

+ +

Among other things, an add-on could:

+ + + +

There are several types of add-ons, but the most common type are extensions.

+ +

Developing extensions

+ +

In the past, there were several toolsets for developing Firefox extensions, but as of November 2017, extensions must be built using WebExtensions APIs. Other toolsets, such as overlay add-ons, bootstrapped add-ons, and the Add-on SDK, are no longer supported.

+ +

If you are writing a new extension, use WebExtensions APIs.

+ +

Extensions written using WebExtensions APIs for Firefox are designed to be cross-browser compatible. In most cases, it will run in Chrome, Edge, and Opera with few if any changes. They are also fully compatible with multiprocess Firefox.
+
+ See the APIs currently supported in Firefox and other browsers. We're continuing to design and implement new APIs in response to developer needs.
+
+ Most of the WebExtensions APIs are also available on Firefox for Android.

+ +

Migrate an existing extension

+ +

If you maintain a legacy extension, such as an XUL overlay, bootstrapped, or Add-on SDK-based extension, you can still port it to use WebExtension APIs. There are some porting resources on MDN.

+ +

For more information about transition support, please visit our wiki page.

+ +

Publishing add-ons

+ +

Addons.mozilla.org, commonly known as "AMO," is Mozilla's official site for developers to list add-ons, and for users to discover them. By uploading your add-on to AMO, you can participate in our community of users and creators and find an audience for your add-on.

+ +

You are not required to list your add-on on AMO, but your add-on must be signed by Mozilla else users will not be able to install it.

+ +

For an overview for the process of publishing your add-on see, Signing and distributing your add-on.

+ +

Other types of add-ons

+ +

In addition to extensions, there are a few other add-on types that allow users to customize Firefox. Those add-ons include:

+ + + +

Contact us

+ +

You can use the links below to get help, keep up to date with news around add-ons and give us feedback.

+ +

Add-ons forum

+ +

Use the Add-ons Discourse forum to discuss all aspects of add-on development and to get help.

+ +

Mailing lists

+ +

Use the dev-addons list to discuss development of the add-ons ecosystem, including the development of the WebExtensions system and of AMO:

+ + + +

IRC

+ +

If you're a fan of IRC (Internet Relay Chat), you can get in touch at:

+ + + +

Report problems

+ +

Security vulnerabilities

+ +

If you discover a security vulnerability in an add-on, even if it is not hosted on a Mozilla site, let us know and we will work with the developer to correct the issue. Please report them confidentially in Bugzilla or by emailing amo-admins@mozilla.com.

+ +

Bugs on addons.mozilla.org (AMO)

+ +

If you find a problem with the site, we'd love to fix it. Please file a bug report and include as much detail as possible.

+ +
{{AddonSidebar}}
diff --git a/files/he/mozilla/add-ons/themes/index.html b/files/he/mozilla/add-ons/themes/index.html new file mode 100644 index 0000000000..4c0c59c553 --- /dev/null +++ b/files/he/mozilla/add-ons/themes/index.html @@ -0,0 +1,49 @@ +--- +title: Themes +slug: Mozilla/Add-ons/Themes +tags: + - Add-ons + - Look & Feel + - NeedsTranslation + - Themes + - TopicStub +translation_of: Mozilla/Add-ons/Themes +--- +

{{AddonSidebar}}

+ +

Themes allow you to change the look and feel of the user interface and personalize it to your tastes. Learn how to create and share themes!

+ +
+
+

Browser Themes

+ +
+
Browser theme concepts
+
Get an introduction to creating themes for the latest versions of Firefox
+
Using the AMO theme generator
+
Use the theme generator to create and submit a new theme to AMO
+
+ +

Lightweight Themes

+ +
+

Lightweight themes have been deprecated and are no longer accepted by AMO. Only browser themes will be accepted going forward.

+
+
+ + +
+ +

 

+ +

 

diff --git a/files/he/mozilla/add-ons/themes/theme_concepts/index.html b/files/he/mozilla/add-ons/themes/theme_concepts/index.html new file mode 100644 index 0000000000..3ca8dedc96 --- /dev/null +++ b/files/he/mozilla/add-ons/themes/theme_concepts/index.html @@ -0,0 +1,248 @@ +--- +title: קונספטי ערכות נושא +slug: Mozilla/Add-ons/Themes/Theme_concepts +tags: + - ערכת נושא + - תוסף +translation_of: Mozilla/Add-ons/Themes/Theme_concepts +--- +
{{AddonSidebar()}}
+ +

ערכות נושא המפותחות באמצעות Iממשקי פיתוח הרחבות רשת בפיירפוקס מאפשרות לך לשנות את מראה הדפדפן על ידי הוספת תמונות לאיזור הכותרות של דפדפן הפיירפוקס: זהו האזור מאחורי סרגל התפריטים, סרגל הכלים, שדה הכתובת,סרגל החיפוש ופס הלשוניות.

+ +

אפשרויות ערכת נושא אלה יכולות להיות מיושמות כערגות נושא סטטיות (למרות שתמונות ערכת הנושא עצמן יכולות להיות מונפשות) או כערכות נושא דינמיות המיוצרות בהרחבת הדפדפן.

+ +
+

אם יש לך ערכת נושא קלת משקל היא תומר לפורמט החדש של ערכות נושא באופן אוטומטי לפני שערכות נושא קלות משקל יוצאות משימוש. אין צורך לנייד את ערכת הנושא שלך. אולם, אנא הרגש/י חופשי/ה לעסכן את ערכת הנושא שלך להשתמש בתכונות החדשות המתוארות כאן.

+
+ +

ערכות נושא סטטיות

+ +

ערכות נושא סטטיות מצויינות על ידי שימוש במשאבים כגון הרחבות דפדפן: קובץ  manifest.json להגדיר רכיבי ערכת נושא עם רכיבים אלה מאוחסניחם באותה תיקייה כמו הקובץ   manifest.json רו בתת-תיקייה. משאבים אלה נארזים אחר-כך בקובץ דחוס לפרסום ב-  addons.mozilla.org (AMO) או בהפצה עצמית. למידע נוסף על הפצה עצמית, בקרו ב- חתימה והפצה של התוסף שלך.

+ +

ץוכלו להשתמש גם ב מחולל ערכות הנושא-ב- AMO ליצור ערכת נושא סטטית. בנוסף, ניתן להשתמש ב- Firefox Color לצפות בהתאמות לערכת הנושא של הדפדפן עם אפשרויות לשתף ולייצא ערכת נושא. .

+ +
+

ערכת נושא ופונקציונליות של הרחבות דפדפן אינן יכולות להיות מוגדרות בחבילה אחת, כמו לכלול ערכת נושא שתשלים הרחבה. אולם ניתן בדרכים תכנותיות לכלול ערכת נושא בתוך הרחבה באמצעות ממשק הפיתוח של ערכת הנושא. ראו  ערכות מושא דינמיות.

+
+ +

הגדרץ ערכת נושא

+ +

ליצירת ערכת נושא (בדוגמא זו ערכת תמונה בודדת פשוטה):

+ + + +

גישות ערכת נושא סטטית

+ +

קיימות שתי גישות ל"ציור" אזור הכותרת של פיירפוקס :  באמצעות תמונה אחת או באמצעות ריבוי תמונות. ניתן לשלב את שתיהן אך יותר קל להתיחחס לכל אחת בנפרד.

+ +

ערכות נושא של תמונה אחת

+ +

זו אפשרות ה"ציור" הבסיסית או המינימלית בה ניתן להגדיר:

+ + + +

על שטח תמונת הכותרת שלך למלא מקסימום גובה של 200 פיקסלים. מקסימום רוחב התמונה נקבע על ידי הרזולוציה של הצג עליו פיירפוקס מציג ובכמה מהצג פיירפוקס משתמש. בפועל, זאת אומרת שיהיה צורך להתיר קוחב של עד 5120 פיקסלים (לדור הבא של צגי 5K). אולם, על פני יצירת תמונה רחבה מאוד גישה עדיפה היא ליצור תמונה יותר צרה עם קצה שמאלי שקוף כך שהיא תדהה לצבע הרקע. לדוגמא, נוכל להשתמש בתמונה הבאה:

+ +

An image of a weta (the common name for a group of about 70 insect species in the families Anostostomatidae and Rhaphidophoridae, endemic to New Zealand) with the left edge fading to total transparency.
+ בשילוב עם צבע רקע משלים לליצירת אפקט זה בכותרת
+ A single image theme using the weta.png image

+ +

ראו פרטים על ערכת נושא זו בדוגמת  ערכות הנושא weta_fade.

+ +

בבירור, ניתן עדיין לספק תמונה רחבה יחידה אם זה עדיף לך.

+ +

ערכות נושא של ריבוי תמונות

+ +

כחלופה ליצירת ערכת נושא בת תמונה אחת, קיימת האופציה להשתמש ביותר תמונות. תמונות אלה יכולות להיות מעוגנות אינדיבידואלית למיקומים בתוך הכותרת, אם האפשרות ליצירת אריח לכל תמונה.

+ +

בתלות באפקט שברצונך ליצור ייתכן ויהיה צורך לדכא את התמונה המחוייבת "headerURL": בתמונה ריקה או שקופה. שימוש בתמונה ריקה או שקופה יעשה , לדוגמא , אם ברצונך להכניס תמונהמיושרת למרכז באריח כמו
+ An image of a weta (the common name for a group of about 70 insect species in the families Anostostomatidae and Rhaphidophoridae, endemic to New Zealand) with the left and right edges fading to total transparency.
+ ליצירת האפקס הזה
+ A single image theme using the additional images option to align an image to the center of the heading and tile it.
+ כאן תוכלו לציין תמונת weta כך:

+ +
"images": {
+  "headerURL": "empty.png",
+  "additional_backgrounds": [ "weta_for_tiling.png"]
+},
+ +

ואת הכנסת התמונות לאריחים כך:

+ +
"properties": {
+  "additional_backgrounds_alignment": [ "top" ],
+  "additional_backgrounds_tiling": [ "repeat"  ]
+},
+ +

פרטים מלאים אודות איך לאתחל ערכת נושא זו ניתן למצוא בדוגמת  ערכות הנושא weta_tiled. פאטים מלאים אודות ישור ואפשרויות יצירת אריחים ניתן למצוא ב - "theme" key description.

+ +

לחלופין, ניתן להשתמש ביותר מתמונה אחת , למשל בשילוב תמונות ה weta המקוריות עם זאת המעוגנת לשמאל הכותרת
+ An image of a weta (the common name for a group of about 70 insect species in the families Anostostomatidae and Rhaphidophoridae, endemic to New Zealand) with the right edge fading to total transparency.
+ ליצירת האפקט
+ A theme using the additional images option to place two mirrored image to the left and right of the browser header.

+ +

בו התמונה מצויינת על ידי:

+ +
"images": {
+  "headerURL": "empty.png",
+  "additional_backgrounds": [ "weta.png", "weta-left.png"]
+},
+ +

והיישור  שלה על ידי:

+ +
"properties": {
+  "additional_backgrounds_alignment": [ "right top" , "left top" ]
+},
+ +

פרטים מלאים אודות איך לאתחל ערכת נושא זו ניתן למצוא בדוגמת   ערכות הנושא  weta_mirror. פרטים מלאים אודות אפשרויות היישור ניתן למצוא ב-  "theme" key description.

+ +

ערכות נושא סטטיות מונפשות

+ +

ניתן ליצור ערכת נושא מונפשת באמצעות פורמט התמונות  APNG , כמו בדוגמת ערכות הנושא animated. אולם, יש לזכור כי אנימציות מהירות כמו זו שבדוגמא יכולה להיות מסיחת דעת מדי עבור ערכת נושא מעשית.

+ +

ניתן גם להנפיש ערכות נושא תכנותית, ובזה נדון בערכות נושא דינמיות.

+ +

עדכון ערכות נושא סטטיות

+ +

אם ערכת הנושא הסטטית שלך מאורחת ב- AMO, ניתן להעלות גרסה חדשה באמצעות Developer Hub על ידי הצעדים הבאים:

+ +
    +
  1. ביקור בעמוד המוצר עבור ההרחבה שלך דרך  Developer Hub
  2. +
  3. בחירת "Upload New Version" בצד שמאל
  4. +
  5. העלאת הקובץ הארוז לוידוא או שינוי באמצעות מחולל ערכות הנושא
  6. +
+ +

עבור ערכות נושא מאורחות עצמית, ניתן להעלות גרסה חדשה דרך AMO על ידי ביצוע הצעדים דלעיל או שיטופלו על ידך דרך כתובת URL מעודכנת  או עדכוני יישום חיצוני. גירסה חדשה תצטרך להיחתם דרך Developer Hub.

+ +
+

אם מעלים קובץ ארוז, מספר הגירסה צריךלהיות גבוה ממספר הגרסה הנוכחית.

+
+ +

ערכות נושא דינמיות

+ +

כחלופה להגדרת ערכת נושא סטטית, ניתן להשתמש בממשק הפיתוח  {{WebExtAPIRef("theme")}} כדי לשלוט בערכת הנושא שבשימוש על ידי פיירפוקס מתוך הרחבת דפדפן. יש מספר מקרי שימוש באפשרות זו:

+ + + +

וכמובן, ניתן לשלב את השתיים ולאגד ערכת נושא הנשלטת על ידי תכנות עם ההרחבה שלך.

+ +

השימוש בממשק ה- {{WebExtAPIRef("theme")}} הוא ישיר. תחילה, יש לבקש  הרשאת  "theme" בקובץ manifest.json של ההרחבה. השלב הגא, בונים אובייקט JSON המכיל אותה אינפורמציה שתשתמשו בה בקובץ manifest.json של ערכת נושא סטטית, לבסוף, יש להעביר את אובייקט ה- JSON בקריאת  {{WebExtAPIRef("theme.update()")}}.

+ +

לדוגמא, הקוד הבא מתוך  dynamic theme example מגדיר את התוכן עבור אלמנטי היום והלילה של ערכת הנושא הדינמית

+ +
const themes = {
+  'day': {
+    images: {
+     headerURL: 'sun.jpg',
+    },
+    colors: {
+     accentcolor: '#CF723F',
+     textcolor: '#111',
+    }
+  },
+  'night': {
+    images: {
+     headerURL: 'moon.jpg',
+    },
+    colors: {
+     accentcolor: '#000',
+     textcolor: '#fff',
+    }
+  }
+};
+ +

עכת הנושא.אובייקט ערכת הנושא מועבר אז ל- {{WebExtAPIRef("theme.update()")}} לשינוי ערכת הנושא של הכותרת, כבקטע קוד זה מתוך אותה דוגמא

+ +
function setTheme(theme) {
+  if (currentTheme === theme) {
+    // No point in changing the theme if it has already been set.
+    return;
+  }
+  currentTheme = theme;
+  browser.theme.update(themes[theme]);
+}
+ +

לימדו עוד אודות ערכות נושא דינמיות, וראו דוגמאות נוספות בסרטון הבא::

+ +

{{EmbedYouTube("ycckyrUN0AY")}}

+ +

+ +

אם טרם יצרת הרחבת דפדפן, צפה/י ב- ההרחבה הראשונה שלך להדרכה צעד-צעד.

+ +

תאימות בין דפדפנים

+ +

קיימת תאימות מוגבלת בין ערכות נושא בדפדפנים המובילים. לדפדפן אופרה גישה שונה לחלוטין , וערכות הנושא של  Microsoft Edge אינן פתוחות עדיין למפחתים/ות.

+ +

יש איזו שהיא תאימות בין ערכות נושא של פיירפוקס  ועאכות נושא של כרום, בתנאי שהיכולת לנייד ערכת נושא של הרחבה בת תמונה יחידה מפיירפוקס לכרום.  זה נעשה על ידי תיקון המפתחות ב-manifest.json  כלהלן:

+ + + +

בשתומת לב לכך ש- "frame": ו- "tab_background_text": תומכים רק בהגדרות מערך צבעים  RGB בכרום.

+ +

אז, בדוגמת ערכת הנושא בת התמונה היחידה (weta_fade) יכולה להיתמך בכרום  באמצעות קובץ ה-manifest.json הבא:

+ +
{
+  "manifest_version": 2,
+  "version": "1.0",
+  "name": "<your_theme_name>",
+  "theme": {
+    "images": {
+      "theme_frame": "weta.png"
+    },
+    "colors": {
+      "frame": [ 173 , 176 , 159 ],
+      "tab_background_text": [ 0 , 0 , 0 ]
+    }
+  }
+}
+ +

אולם, יהיו מספר הבדלים

+ + + +

The basic theme example using the Chrome compatible manifest.json keys, showing the differences in how those keys are implemented.

+ +

לעוד מידע , ראו רשימות ב-Chrome compatibility.

diff --git a/files/he/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html b/files/he/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html new file mode 100644 index 0000000000..049dfbd389 --- /dev/null +++ b/files/he/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html @@ -0,0 +1,144 @@ +--- +title: אנטומיה של הרחבה +slug: Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension +translation_of: Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension +--- +
{{AddonSidebar}}
+ +

הרחבה מורכבת מאוסף של קבצים, ארוזים להפצה והתקנה. במאמר זה, נסקור במהירות את הקבצים העשויים להיות נוכחים בהרחבה.

+ +

manifest.json

+ +

זהו הקובץ היחיד שחייב להימצא בכל הרחבה הוא כולל מטאדאטה בסיסית כגון שם, גירסה וההרשאות הדרושות. הוא גם מספק מצביעים לקבצים אחרים בהרחבה.

+ +

מניפסט זה יכול לכלול גם מצביעים לעוד מספר טיפוסי קבצים 

+ + + +

+ +

ראו דף סימוכין לממשק  manifest.json לכל הפרטים.

+ +

יחד עם כל אלה הרשומים במניפסט , הרחבה יכולה לכלול גם   דפי הרחבה נוספים וקבצים תומכים.

+ +

תסריטי רקע

+ +

הרחבות צריכות לעתים קרובות לשמור מצב ארוך טווח או לבצע םעולות ארוכות טווח ללא תלות בזמן החיים של דף רשת זה או אחר או בחלון דפדפן. בשביל זה יש תסריטי רקע.

+ +

תסריטי רקע נטענים מייד כאשר ההרחבה נטענת ונשארים טעונים עד שההרחבה מושבתת או מוסרת. נתין להשתמש בכל אחד מממשקי פיתוח הרחבות הרשת בתסריט, כל עוד ביקשת את ההרשאות הדרושות.

+ +

ציון תסריטי הרקע

+ +

ניתן לכלול תסריט רקע באמצעות המפתח  background  ב-"manifest.json":

+ +
// manifest.json
+
+"background": {
+  "scripts": ["background-script.js"]
+}
+ +

ניתן לציין מספר תסריטי רקע: אם תעשו כן, הם  ירוצו באותו הקשר. , בדיוק כמו תסריטים מרובים הנטענים לתוך דף רשת יחיד.

+ +

במקום לציין תסריטי רקע, ניתן לציין דף רקע שיש לו יתרונות נוספים של תמיכה במודולי ES6:

+ +

manifest.json

+ +
// manifest.json
+
+"background": {
+  "page": "background-page.html"
+}
+ +

background-page.html

+ +
<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8">
+    <script type="module" src="background-script.js"></script>
+  </head>
+</html>
+ +

סביבת תסריטי רקע

+ +

ממשקי פיותח DOM

+ +

תסריטי רקע רצים בהקשר של דף מיוחד הקרוי דף רקע . זה נותן להם את המשתנה הגלובלי window, יחד עם כל ממשקי פיתוח ה-  DOM המסופקים עם אובייקט זה

+ +
+

 בפיירפוקס תסריטי רקע אינם תומכים בשימוש ב-, background pages do not support - alert(), confirm(), או prompt().

+
+ +

ממשקי פיתוח הרחבות רשת

+ +

תסריטי רקע יכולים להשתמש בכל ממשקי פיתוח הרחבות הרשת בתסריט, כל עוד להרחבה יש את ההרשאות הדרושות.

+ +

גישה בין מקורות

+ +

תסריטי רקע יכולים ליצור בקשות XHR לכל מארח עבורו יש להם  הרשאות מארח.

+ +

תוכן ברשת

+ +

תסריטי רקע אינם מקבלים גישה ישירה לדפי רשת. אולם הם יכולים לטעון,  תסריטי תוכן לתוך דפי רשת ויכולים  לתקשר עם תסריטי תוכן אלה באמצעות ממשקי פיתוח להעברת הודעות

+ +

מדיניות אבטחת תוכן

+ +

תסריטי תוכן מוגבלים מביצוע פעולות בעלות פוטנציאל סיכון , כמו שימוש ב-eval() .דרך מדיניות אבטחת תוכן. ראו מדיניות אבטחת תוכן לפרטים נוספים על כך.

+ +

סרגלים צדדיים, חלונות קופצים, דפי אופציות

+ +

ההרחבה שלך יכולה לכלול רכיבי ממשק משתמש שונים שהתוכן שלהם מוגדר על ידי מסמך HTML :

+ + + +

עבור כל אחד מרכיבים אלה ניתן ליצור קובץ HTML ולהצביע אליו באמצעות תכונה ספציפית ב-  manifest.json. קובץ ה- HTML יכול לכלול  CSS וקבצי ג'אווהסקריפט, בדיוק כמו דף רשת נורמלי.

+ +

כל אלה הם טיפוס של  דפי הרחבה, ושלא כמו דף רשת רגיל, הג'אווהסקריפט שלך יכול להשתמש בכל אותם ממשקי פיתוח פריבילגיים להרחבות רשת כמו תסריט הרקע. הם יכולים גם לגשת ישירות למשתנים בדך הרקע באמצעות  {{WebExtAPIRef("runtime.getBackgroundPage()")}}.

+ +

דפי הרחבה

+ +

ניתן לכלול בהרחבה שלך  גם מסמכי  HTML שאינם מחוברים לרכיב ממשק משתמש מוגדר מראש כלשהו . שלא כמו מסמכים שניתן לספק עבור סרגלים צדדיים, חלונות קופצים, או דפי אופציות, אין להם הגדרה ב- manifest.json. אולם , יש להם גישה לכל אותם ממשקי פיתוח הרחבות רשת פריבילגיים כמו תסריט הרקע שלך.

+ +

באופן טיפוסי, דף כזה ייטען באמצעות  {{WebExtAPIRef("windows.create()")}} או {{WebExtAPIRef("tabs.create()")}}.

+ +

ראו דפי הרחבה כדי ללמוד עוד.

+ +

Content scripts

+ +

Use content scripts to access and manipulate web pages. Content scripts are loaded into web pages and run in the context of that particular page.

+ +

Content scripts are extension-provided scripts which run in the context of a web page; this differs from scripts which are loaded by the page itself, including those which are provided in {{HTMLElement("script")}} elements within the page.

+ +

Content scripts can see and manipulate the page's DOM, just like normal scripts loaded by the page.

+ +

Unlike normal page scripts, they can:

+ + + +

Content scripts cannot directly access normal page scripts but can exchange messages with them using the standard window.postMessage() API.

+ +

Usually, when we talk about content scripts, we are referring to JavaScript, but you can inject CSS into web pages using the same mechanism.

+ +

See the content scripts article to learn more.

+ +

משאבים נגישים לרשת

+ +

משאבים נגישים לרשת עם משאבים כגון תמונות, HTML, CSS, ו- JavaScript הנכללים בהרחבה  וייתכן שתרצו לאפשר להם גישה לתסריטי תוכן ותסריטי דף. ניתן להפנות למשאבים הנוצרים נגישים לרשת על ידי תסריטי דף ותסריטי תוכן באמצעות סכמת   URI מיוחדת.

+ +

לדוגמא, אם תסריט תוכן מעוניין להכניס קצת תמונות לתוך דפי רשת , ניתן לכלול אותם בהרחבה ולעשות אותם נגישים לרשת . אז תסריט התוכן יכול ליצור ולהוסיף תגיות   img המפנות לתמונות דרך המאפיין src.

+ +

כדי ללמוד עוד, אטו טת התיעוד עבור המפתח web_accessible_resources  ב-manifest.json .

diff --git a/files/he/mozilla/add-ons/webextensions/api/alarms/index.html b/files/he/mozilla/add-ons/webextensions/api/alarms/index.html new file mode 100644 index 0000000000..30a42d1d02 --- /dev/null +++ b/files/he/mozilla/add-ons/webextensions/api/alarms/index.html @@ -0,0 +1,60 @@ +--- +title: השכמות +slug: Mozilla/Add-ons/WebExtensions/API/alarms +tags: + - API + - הרחבות + - הרחבות רשת + - השכמות + - ממשק + - ממשק פיתוח + - סימוכין +translation_of: Mozilla/Add-ons/WebExtensions/API/alarms +--- +
{{AddonSidebar}}
+ +

מתזמנות קוד לרוץ בזמן שצויין. זה כמו setTimeout() ו- setInterval(), פרט לכך שפונקציות אלה לא עובדות עם דפי רקע הנטענים על פי דרישה. השכמות אינן מתמידות לאורך מפגשי הדפדפן.

+ +

לשימוש בממשק פיתוח זה יש לכלול   הרשאת "alarms".

+ +

טיפוסים

+ +
+
{{WebExtAPIRef("alarms.Alarm")}}
+
מידע אודות השכמה מסוימת.
+
+ +

שיטות

+ +
+
{{WebExtAPIRef("alarms.clear()")}}
+
מחק השכמה מסויימת בהינתן שמה.
+
{{WebExtAPIRef("alarms.clearAll()")}}
+
מחק את כל ההשכמות המתוזמנות.
+
{{WebExtAPIRef("alarms.create()")}}
+
צור השכמה חדשה.
+
{{WebExtAPIRef("alarms.get()")}}
+
שלוף השכמה מסויימת בהינתן שמה.
+
{{WebExtAPIRef("alarms.getAll()")}}
+
שלוף את כל ההשכמות המתוזמנות.
+
+ +

אירועים

+ +
+
{{WebExtAPIRef("alarms.onAlarm")}}
+
משוגר כאשר מגיע זמן ההשכמה.
+
+ +

{{WebExtExamples("h2")}}

+ +

תאימות דפדפנים

+ +

{{Compat("webextensions.api.alarms")}}

+ +
Acknowledgements + +

ממשק פיתוח זה מבוסס על ממשק הפיתוח chrome.alarms של כרומיום.

+ +

מידע התאימות של Microsoft Edge סופק על ידי תאגיד מיקרוסופט וכלול פה תחת רשיון Creative Commons Attribution 3.0 ארה"ב.

+
diff --git a/files/he/mozilla/add-ons/webextensions/api/browseraction/index.html b/files/he/mozilla/add-ons/webextensions/api/browseraction/index.html new file mode 100644 index 0000000000..195f81d304 --- /dev/null +++ b/files/he/mozilla/add-ons/webextensions/api/browseraction/index.html @@ -0,0 +1,124 @@ +--- +title: browserAction +slug: Mozilla/Add-ons/WebExtensions/API/browserAction +translation_of: Mozilla/Add-ons/WebExtensions/API/browserAction +--- +
{{AddonSidebar}}
+ +

מוסיף כפתור לסרגל הכלים של הדפדפן.

+ +

 פעולת דפדפן הינה כפתור בסרגל הכלים של הדפדפן.

+ +

ניתן לקשר חלון קופץ עם הכפתור. החלון הקופץ מצויין באמצעות HTML, CSS וג'אווה-סקריפט , בדומה לדף רשת רגיל. לקוד ג'אווה-סקריפט המורץ בחלון הקופץ גישה לכל ממשקי פיתוח היישומים של הרחבת הרשת כמו תסריטי הרקע שלך, אך ההקשר הגלובלי שלו הוא החלון הקופץ, ולא הדף הנוכחי המוצג על ידי הדפדפן. כדי להספיע לע הדפים מהרשת יש לתקשר איתם דרך  messages.

+ +

If you specify a popup, it will be shown — and the content will be loaded — when the user clicks the icon. If you do not specify a popup, then when the user clicks the icon an event is dispatched to your extension.

+ +

You can define most of a browser action's properties declaratively using the browser_action key in the manifest.json.

+ +

With the browserAction API, you can:

+ + + +

Types

+ +
+
{{WebExtAPIRef("browserAction.ColorArray")}}
+
An array of four integers in the range 0-255 defining an RGBA color.
+
{{WebExtAPIRef("browserAction.ImageDataType")}}
+
Pixel data for an image. Must be an ImageData object (for example, from a {{htmlelement("canvas")}} element).
+
+ +

Functions

+ +
+
{{WebExtAPIRef("browserAction.setTitle()")}}
+
Sets the browser action's title. This will be displayed in a tooltip.
+
{{WebExtAPIRef("browserAction.getTitle()")}}
+
Gets the browser action's title.
+
{{WebExtAPIRef("browserAction.setIcon()")}}
+
Sets the browser action's icon.
+
{{WebExtAPIRef("browserAction.setPopup()")}}
+
Sets the HTML document to be opened as a popup when the user clicks on the browser action's icon.
+
{{WebExtAPIRef("browserAction.getPopup()")}}
+
Gets the HTML document set as the browser action's popup.
+
{{WebExtAPIRef("browserAction.openPopup()")}}
+
Open the browser action's popup.
+
{{WebExtAPIRef("browserAction.setBadgeText()")}}
+
Sets the browser action's badge text. The badge is displayed on top of the icon.
+
{{WebExtAPIRef("browserAction.getBadgeText()")}}
+
Gets the browser action's badge text.
+
{{WebExtAPIRef("browserAction.setBadgeBackgroundColor()")}}
+
Sets the badge's background color.
+
{{WebExtAPIRef("browserAction.getBadgeBackgroundColor()")}}
+
Gets the badge's background color.
+
{{WebExtAPIRef("browserAction.setBadgeTextColor()")}}
+
Sets the badge's text color.
+
{{WebExtAPIRef("browserAction.getBadgeTextColor()")}}
+
Gets the badge's text color.
+
{{WebExtAPIRef("browserAction.enable()")}}
+
Enables the browser action for a tab. By default, browser actions are enabled for all tabs.
+
{{WebExtAPIRef("browserAction.disable()")}}
+
Disables the browser action for a tab, meaning that it cannot be clicked when that tab is active.
+
{{WebExtAPIRef("browserAction.isEnabled()")}}
+
Checks whether the browser action is enabled or not.
+
+ +

Events

+ +
+
{{WebExtAPIRef("browserAction.onClicked")}}
+
Fired when a browser action icon is clicked. This event will not fire if the browser action has a popup.
+
+ +

Browser compatibility

+ +

{{Compat("webextensions.api.browserAction")}}

+ + + +

{{WebExtExamples("h2")}}

+ +
Acknowledgements + +

This API is based on Chromium's chrome.browserAction API. This documentation is derived from browser_action.json in the Chromium code.

+ +

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

+
+ + diff --git a/files/he/mozilla/add-ons/webextensions/api/index.html b/files/he/mozilla/add-ons/webextensions/api/index.html new file mode 100644 index 0000000000..4cbd4a2a8a --- /dev/null +++ b/files/he/mozilla/add-ons/webextensions/api/index.html @@ -0,0 +1,55 @@ +--- +title: ממשקי פיתוח יישומים בג'אווה-סקריפט +slug: Mozilla/Add-ons/WebExtensions/API +tags: + - NeedsTranslation + - TopicStub +translation_of: Mozilla/Add-ons/WebExtensions/API +--- +
{{AddonSidebar}}
+ +
+

בממשקי פיתוח היישומים עבור הרחבות רשת בג'אווה-סקריפט ניתן להשתמש בתוך

+ +

  תסריטי הרקע של ההרחבה ובכל המסמכים האחרים הכלולים בהרחבה, כולל  browser action or page action popups, sidebars, options pages, or new tab pages. A few of these APIs can also be accessed by an extension's content scripts (see the list in the content script guide).

+ +

To use the more powerful APIs you need to request permission in your extension's manifest.json.

+ +

You can access the APIs using the browser namespace:

+ +
function logTabs(tabs) {
+  console.log(tabs);
+}
+
+browser.tabs.query({currentWindow: true}, logTabs);
+
+ +
+

Many of the APIs are asynchronous, returning a Promise:

+ +
function logCookie(c) {
+  console.log(c);
+}
+
+function logError(e) {
+  console.error(e);
+}
+
+var setCookie = browser.cookies.setokie.then(logCookie, logError);
+
+ +
+

Note that this is different from Google Chrome's extension system, which uses the chrome namespace instead of browser, and which uses callbacks instead of promises for asynchronous functions. As a porting aid, the Firefox implementation of WebExtensions APIs supports chrome and callbacks as well as browser and promises. Mozilla has also written a polyfill which enables code that uses browser and promises to work unchanged in Chrome: https://github.com/mozilla/webextension-polyfill.

+ +

Firefox also implements these APIs under the chrome namespace using callbacks. This allows code written for Chrome to run largely unchanged in Firefox for the APIs documented here.

+ +

Microsoft Edge uses the browser namespace, but doesn't yet support promise-based asynchronous APIs. In Edge, for the time being, asynchronous APIs must use callbacks.

+ +

Not all browsers support all the APIs: for the details, see Browser support for JavaScript APIs.

+ +

JavaScript API listing

+ +

See below for a complete list of JavaScript APIs:

+
+ +
{{SubpagesWithSummaries}}
diff --git a/files/he/mozilla/add-ons/webextensions/api/storage/index.html b/files/he/mozilla/add-ons/webextensions/api/storage/index.html new file mode 100644 index 0000000000..f866b07efa --- /dev/null +++ b/files/he/mozilla/add-ons/webextensions/api/storage/index.html @@ -0,0 +1,102 @@ +--- +title: storage +slug: Mozilla/Add-ons/WebExtensions/API/storage +translation_of: Mozilla/Add-ons/WebExtensions/API/storage +--- +
{{AddonSidebar}}
+ +

מאפשר להרחבות לאחסן ולשלוף נתונים, ולהאזין לשינויים בפריטים המאוחסנים.

+ +

מערכת האחסון מבוססת על ממשק פיתוח היישומים Web Storage, עם מספר הבדלים. בין ההבדלים ניתן למצוא כי:

+ + + +

To use this API you need to include the "storage" permission in your manifest.json file.

+ +

Each extension has its own storage area, which can be split into different types of storage.

+ +

Although this API is similar to {{domxref("Window.localStorage")}} it is recommended that you don't use Window.localStorage in the extension code to store extension-related data. Firefox will clear data stored by extensions using the localStorage API in various scenarios where users clear their browsing history and data for privacy reasons, while data saved using the storage.local API will be correctly persisted in these scenarios.

+ +

You can examine the stored data under the Extension Storage item in the Storage Inspector tab of the developer toolbox, accessible from about:debugging.

+ +
The storage area is not encrypted and shouldn't be used for storing confidential user information.
+ +

Types

+ +
+
{{WebExtAPIRef("storage.StorageArea")}}
+
An object representing a storage area.
+
{{WebExtAPIRef("storage.StorageChange")}}
+
An object representing a change to a storage area.
+
+ +

Properties

+ +

storage has three properties, which represent the different types of available storage area.

+ +
+
{{WebExtAPIRef("storage.sync")}}
+
Represents the sync storage area. Items in sync storage are synced by the browser, and are available across all instances of that browser that the user is logged into, across different devices.
+
{{WebExtAPIRef("storage.local")}}
+
Represents the local storage area. Items in local storage are local to the machine the extension was installed on.
+
{{WebExtAPIRef("storage.managed")}}
+
Represents the managed storage area. Items in managed storage are set by the domain administrator and are read-only for the extension. Trying to modify this namespace results in an error.
+
+ +

Events

+ +
+
{{WebExtAPIRef("storage.onChanged")}}
+
Fired when one or more items change in a storage area.
+
+ +

Browser compatibility

+ + + +

{{Compat("webextensions.api.storage")}}

+ +

{{WebExtExamples("h2")}}

+ +
Acknowledgements + +

This API is based on Chromium's chrome.storage API. This documentation is derived from storage.json in the Chromium code.

+ +

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

+
+ + diff --git a/files/he/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html b/files/he/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html new file mode 100644 index 0000000000..90b11fb246 --- /dev/null +++ b/files/he/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html @@ -0,0 +1,24 @@ +--- +title: Browser support for JavaScript APIs +slug: Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs +tags: + - הרחבות רשת + - סימוכין +translation_of: Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs +--- +
{{AddonSidebar}}
+ + + +

{{WebExtAllCompatTables}}

+ +
תודות + +

נתוני התאימות לדפדפן Microsoft Edge מסופקים על ידי תאגיד מיקרוסופט ונכללים כאם ץחת רשיון Creative Commons Attribution 3.0 ארה"ב.

+
+ +

See also

+ + diff --git a/files/he/mozilla/add-ons/webextensions/content_scripts/index.html b/files/he/mozilla/add-ons/webextensions/content_scripts/index.html new file mode 100644 index 0000000000..727114978d --- /dev/null +++ b/files/he/mozilla/add-ons/webextensions/content_scripts/index.html @@ -0,0 +1,493 @@ +--- +title: תסריטי תוכן +slug: Mozilla/Add-ons/WebExtensions/Content_scripts +tags: + - הרחבות רשת +translation_of: Mozilla/Add-ons/WebExtensions/Content_scripts +--- +
{{AddonSidebar}}
+ +

תסריט תוכן הוא חלק מההרחבה שלך שרץ בהקשר של דף מסויים ברשת  (בניגוד לתסריטי רקע שהם חלק מהרחבה, או תסריטים שהם חלק מאתר הרשת עצמו , כגון אלה הנטענים באמצעות אלמנט ה-{{HTMLElement("script")}} ).

+ +

תסריטי רקע יכולים לגשת לכל  ממשקי הפיתוח בג'אווהסקריפט של הרחבות הרשת,   אך אינם ניגשים ישירות לתוכן של עמודי רשת.  לכן אם ההרחבה שלך צריכה לעשות זאת, עליך לכתוב תסריט תוכן.

+ +

בדיוק כפי שהתסריטים נטענים על ידי דפי רשת נורמליים, תסריטי תוכן יכולים לקרוא ולשנות תוכן הדפים שלהם באמצעות ממשקי פיתוח יישומי DOM.

+ +

תסריטי תוכן יכולים לגשת רק לתת קבוצה קטנה של ממשקי פיתוח הרחבות הרשת,   אך לתקשר עם תסריטי רקע באמצעות מערכת שליחת הודעות, ובאמצעותן לגשת בעקיפין לממשקי הפיתוח של הרחבות הרשת.

+ +
+

לתשומת לבך תסריטי תוכן חסומים במתחמים הבאים:

+ + + +

נסיון להחדיר תסריט תוכן לאתרים אלה ייכשל טהעמוד ירשום שגיאת  CSP ללוג.

+ +

משום שמגבלות אלו כוללות את  addons.mozilla.org, משתמשים עשויים לנסות להשתמש בהרחבה שלך מיד אחרי ההתקנה —רק כדי לגלות שאינה עובדת! ייתכן ותרצה/י להוסיף אזהרה הולמת, או   דף onboarding להרחיק משתמשים מ- addons.mozilla.org.

+
+ +
+

ערכים הנוספים לסקופ הגלובלי של תסריט תוכן באמצעות var foo או window.foo = "bar" עלולים להיעלם עקב באג 1408996.

+
+ +

טעינת תסריט תוכן

+ +

ניתן לטעון תסריט תוכן לאתר רשת בשלוש דרכים:

+ +
    +
  1. בעת ההתקנה, לתוך דפים התואמים תבניות URL: באמצעות מפתח ה-content_scripts בקובץ ה-manifest.json שלך, ניתן  לבקש מהדפדפן לטעון תסריט תוכן בכל פעם שהדפדפן מעלה דף שה-URL שלו תואם תבנית נתונה.
  2. +
  3. בזמן ריצה, לתוך דפים התואמים תבניתו URL : באמצעות ממשק פיתוח היישומים {{WebExtAPIRef("contentScripts")}} API, ניתן לבקש מהדפדפן לטעון  תסריט תוכן בכל ]עפ שהדפדפן טוען דף שה-URL שלו  תואם תבנית נתונה matches a given pattern. זה בפשטות כמו בשיטה  (1), פרט לכך שניתן להוסיף ולהסיר תסריט תוכן בזמן ריצה.
  4. +
  5. בזמן ריצה, לתוך לשוניות מסוימות  into specific tabs: באמצאות צצשק הפיתוח  tabs.executeScript() , ניתן לטעון תסריט תוכן בכל עת שיהיה ברצונך: למשל, סתגובה להקשת משתמש/ת על פעולת דפדפן.
  6. +
+ +

קיים רק סקופ גלובלי אחד למסגרת, להרחבה. זאת אומרת שניתן לגשת למשתני תסריט תוכן אחד ישירות על ידי תסריט תוכן אחר , ללא קשר לדרך בה נטען תסריט התוכן.

+ +

באמצעות שיטות (1) ו- (2), ניתן לטעון תסריטים לתוך דפים שה- URL-ים שלהם  יכולים להיות מיוצגים באמצעות תבניות התאמה.

+ +

באמצעות שיטה (3), ניתן גם לטעון תסריטים לתוך דפים ארוזים עם ההרחבה שלך, אך לא ניתן לטעון תסריטים לתוך דפי דפדפן בעלי פריבילגיה  (כגון "about:debugging" או "about:addons").

+ +

סביבת תסריטי תוכן

+ +

גישה ל-DOM

+ +

תסריטים יכולים לגשת ולשנות את ה-DOM של הדף , בדיוק כפי שיכולים לעשות זת תסריטי דף נורמליים. הם יכולים לראות גם שינווים שנעשו ב- DOM על ידי תסריטי דפים.

+ +

אולם, תסריטי תוכן מקבלים "מראה נקי של ה-DOM". כלומר::

+ + + +

בפיירפוקס התנהגות זו קרויה ראיית רנטגן.

+ +

חשבו על דף רשת כזה:

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
+  </head>
+
+  <body>
+    <script src="page-scripts/page-script.js"></script>
+  </body>
+</html>
+ +

התסריט "page-script.js" עושה את זה:

+ +
// page-script.js
+
+// add a new element to the DOM
+var p = document.createElement("p");
+p.textContent = "This paragraph was added by a page script.";
+p.setAttribute("id", "page-script-para");
+document.body.appendChild(p);
+
+// define a new property on the window
+window.foo = "This global variable was added by a page script";
+
+// redefine the built-in window.confirm() function
+window.confirm = function() {
+  alert("The page script has also redefined 'confirm'");
+}
+ +

כעת  הרחבה מחדירה תסריט תוכן לתוך הדף:

+ +
// content-script.js
+
+// can access and modify the DOM
+var pageScriptPara = document.getElementById("page-script-para");
+pageScriptPara.style.backgroundColor = "blue";
+
+// can't see page-script-added properties
+console.log(window.foo);  // undefined
+
+// sees the original form of redefined properties
+window.confirm("Are you sure?"); // calls the original window.confirm()
+ +

אותו הדבר נכון גם להיפך: תסריטי דף אינם יכולים לראות משתני ג'אווהסקריפט  שנוספו על ידי תסריטי תוכן

+ +

זאת אומרת שתסריטי תוכן יכולים להסתמך על תכונות  DOM שהתנהגותן צפויה. , בלי להיות מודאגים מהתנגשויות משתנים עם משתנים מתסריטי הדף.

+ +

אחת ההשלכות המעשיות של התנהגות זו היא שלתסריט תוכן לא תהיה גישה לאף ספריית ד'אווהסקריפט שנטענה על ידי הדף. לכן לדוגמא, אם דף מכיל jQuery, תסריט התוכן לא יוכל לראותו.

+ +

היה ותסריט תוכן כן רוצה להשתמש בספריית ג'אווהסקריפט, הספריה עצנה צריכה להיות מוחדרת כתסריט תוכן לצד תסריט התוכן המעוניין להשתמש בה::

+ +
"content_scripts": [
+  {
+    "matches": ["*://*.mozilla.org/*"],
+    "js": ["jquery.js", "content-script.js"]
+  }
+]
+ +
+

לתשומת לבך: פיירפוקס כן מספק כמה ממשקי פיתוח יישומים המאפשרים לתסריטי תוכן לגשת לאובייקטי ג'אווהסקריפט הנוצרים על ידי תסריטי דף, ולחשוף את אובייקטי הג'אווהסקריפט שלהם לתסריטי דף.

+ +

ראו  שיתוף אובייקטים עם תסריטי דף לפרטים נוספים.

+
+ +

ממשקי פיתוח יישומים של הרחבות רשת

+ +

בנוסף לממשקי הפיתוח הסטנדרטיים של ה-DOM , ,תסריטי התוכן יכולים להשתמש בממשקי פיתוח היישומים הבאים של הרחבות הרשת:

+ +

מתוך extension:

+ + + +

מתוך runtime:

+ + + +

מתוך i18n:

+ + + +

מתוך menus:

+ + + +

הכל מתוך storage.

+ +

XHR ו-Fetch

+ +

.תסריטי תוכן יכולים להכין בקשות באמצעות ממשקי פיתוח היישומים window.XMLHttpRequest ו- window.fetch().

+ +
+

בפיירפוקס, בקשות תסריטי התוכן (לדוגמא, באמצעות fetch()) קורות בהקשר של הרחבה, כך שיש לספק כתובת  URL מוחלטת  כדי להתייחס לתוכן דף. בכרום, בקשות אלה קורות בהקשר של דף, כך שכתובות ה-URL הן יחסיות,  לדוגמא, /api נשלחת ל- https://[current page URL]/api.

+
+ +

תסריטי תוכן מקבלים את אותן פריבילגיות חוצות מתחמים כמו שאר ההרחבות, כך שאם הרחבה בקשה גישה חוצת מתחמים עבור מתחם באמצעות מפתח  permissions ב- manifest.json, אזי תסריט התוכן יקבל גישה גם למתחם זה. 

+ +

זה יושג על ידי חשיפת יותר מופעי   XHR ו- fetch  בעלי יותר פריבילגיות בתסריט התוכן, להם תופעת הלוואי של אי הגדרת כותרות הorigin והreferer כמו לבקשות מהדף עצמו, לעתים תכופות זה מועדף כדי למנוע מבקשה לחשוף את הטבע חוצה המקורות שלה.  מגרסה 58 ואילך  הרחבות הצריכות לבצע בקשות המתנהגות כאילו משלחו מהתוכן עצמו  יכולות להשתמש ב- content.XMLHttpRequest וב-content.fetch() במקום. להרחבות חוצות דפדפנים נוכחותן חייבת להיו מגולת תכונות.

+ +

תקשורת עם תסריטי רקע

+ +

למרות שתסריטי תוכן אינם יכולים לגשת ישירות לממשקי פיתוח של הרחבות רשת, הם יכולים להתקשר עם תסריטי הרקע של ההרחבות באמצעות ממשקי הפיתוח של שליחת ההודעות ולכן יכולים לגשת בעקיפין לכל אותם הממשקים שתסריטי הרקע יכולים.

+ +

קיימות שתי תבניות בסיסיות להתקשרות בין תסריטי הרקע לתסריטי התוכן: ניתן לשלוח הודעות בודדות, עם אפשרות למענה, או להגדיר התחברות לטווח יותר ארוך בין שני הצדדים, ולהחליף הודעות באמצעות התחברות זאת.

+ +

הודעות בודדות

+ +

לשליחת הודעה בודדת עם אפשרות למענה, ניתן להשתמש בממשקי הפיתוח הבאים:

+ + + + + + + + + + + + + + + + + + + + + +
בתסריט התוכןבתסריט הרקע
שליחת הודעהbrowser.runtime.sendMessage()browser.tabs.sendMessage()
קבלת הודעהbrowser.runtime.onMessagebrowser.runtime.onMessage
+ +

לדוגמא, להלן תסריט תוכן המאזין לאירועי להקלקה בדף הרשת.

+ +

עם ההקלקה הייתה על קישור, יישלח URL המטרה לדף הרקע:

+ +
// content-script.js
+
+window.addEventListener("click", notifyExtension);
+
+function notifyExtension(e) {
+  if (e.target.tagName != "A") {
+    return;
+  }
+  browser.runtime.sendMessage({"url": e.target.href});
+}
+ +

תסריט הרקע מאזין להודעות האלה ומציג התראה באמצעוץ ממשק ה-notifications :

+ +
// background-script.js
+
+browser.runtime.onMessage.addListener(notify);
+
+function notify(message) {
+  browser.notifications.create({
+    "type": "basic",
+    "iconUrl": browser.extension.getURL("link.png"),
+    "title": "You clicked a link!",
+    "message": message.url
+  });
+}
+
+ +

(הקוד לדוגמא מעובד קלות מהדוגמא notify-link-clicks-i18n   ב-GitHub.)

+ +

טיפול בהודעות מבוסס התחברות

+ +

שליחת הודעות בודדות עלול להיות מסורבל אם מתבצעת תחלופה מרובה של הודעות בין תסריט רקע לתסריט תוכן. כך שעל תבנית חליפית להיווסד לצורך התחברות לטוח ארוך יותר בין שני ההקשרים, ולהשתמש בהתחברות זו לחילופי הודעות.

+ +

לכל צד יש אובייקט runtime.Port, המשמש החלפת הודעות.

+ +

ליצירת התחברות:

+ + + +

זה מחזיר אובייקט מסוג runtime.Port.

+ + + +

ברגע שלכל צד יש פתחה , שני הצדדים יכולים:

+ + + +

לדוגמא, מייד כשנטען, תסריט התוכן:

+ + + +
// content-script.js
+
+var myPort = browser.runtime.connect({name:"port-from-cs"});
+myPort.postMessage({greeting: "hello from content script"});
+
+myPort.onMessage.addListener(function(m) {
+  console.log("In content script, received message from background script: ");
+  console.log(m.greeting);
+});
+
+document.body.addEventListener("click", function() {
+  myPort.postMessage({greeting: "they clicked the page!"});
+});
+ +

תסריט הרקע המכותב:

+ + + +
// background-script.js
+
+var portFromCS;
+
+function connected(p) {
+  portFromCS = p;
+  portFromCS.postMessage({greeting: "hi there content script!"});
+  portFromCS.onMessage.addListener(function(m) {
+    console.log("In background script, received message from content script");
+    console.log(m.greeting);
+  });
+}
+
+browser.runtime.onConnect.addListener(connected);
+
+browser.browserAction.onClicked.addListener(function() {
+  portFromCS.postMessage({greeting: "they clicked the button!"});
+});
+
+ +

תסריטי תוכן מרובים

+ +

אם יש לך תסריטי תוכן מרובים המתקשרים בו זמנית, ייתכן שתרצה/י לאחסן כל התחברות במערך.

+ + + +
// background-script.js
+
+var ports = []
+
+function connected(p) {
+  ports[p.sender.tab.id]    = p
+  //...
+}
+
+browser.runtime.onConnect.addListener(connected)
+
+browser.browserAction.onClicked.addListener(function() {
+  ports.forEach(p => {
+        p.postMessage({greeting: "they clicked the button!"})
+    })
+});
+
+ + + +

תקשורת עם דף רשת

+ +

למרות שכברירת מחדל תסריט תוכן אינם מקבלים הרשאת גישה לאובייקטים שנוצרו על ידי תסריטי דף, הם יכולים להתקשר עם תסריטי דף באמצעות ממשקי ה-DOM  window.postMessage ו-window.addEventListener .

+ +

לדוגמא:

+ +
// page-script.js
+
+var messenger = document.getElementById("from-page-script");
+
+messenger.addEventListener("click", messageContentScript);
+
+function messageContentScript() {
+  window.postMessage({
+    direction: "from-page-script",
+    message: "Message from the page"
+  }, "*");
+ +
// content-script.js
+
+window.addEventListener("message", function(event) {
+  if (event.source == window &&
+      event.data &&
+      event.data.direction == "from-page-script") {
+    alert("Content script received message: \"" + event.data.message + "\"");
+  }
+});
+ +

לדוגמא שלמה עובדת של זה, בקרו בדף ההדגמה של- GitHub ובצעו את ההוראות

+ +
+

יש לקחת בחשבון שכבל פעם שמתקשרים עם תוכן שאין בו אמון בדרך זו, יש לנקוט זהירות רבה. הרחבות הן קוד בעל פריבילגיות שיכולות להיות לו יכולות בעלות כוח עצום, ודפי תוכן עויינים יכולים לרמות אותם בקלות לדשת ליכולות אלה.

+ +

לצורך דוגמא טריוויאלית, הניחו כי קוד של תסריט תוכן שמקבל את ההודעה עושה דבר כזה:

+ +
// content-script.js
+
+window.addEventListener("message", function(event) {
+  if (event.source == window &&
+      event.data.direction &&
+      event.data.direction == "from-page-script") {
+    eval(event.data.message);
+  }
+});
+ +

כעת תסריט הדף יכול להריץ כל קוד עם כל הפריביליגיות של תסריט התוכן.

+
+ +

שימוש ב- eval() בתסריטי תוכן

+ +

בכרום, eval() תמיד מריץ קוד בהקשר של תסריט התוכן, לא בהקשר של הדף.

+ +

בפיירפוקס:

+ + + +

לדוגמא, ניקח תסריט תוכן כזה:

+ +
// content-script.js
+
+window.eval('window.x = 1;');
+eval('window.y = 2');
+
+console.log(`In content script, window.x: ${window.x}`);
+console.log(`In content script, window.y: ${window.y}`);
+
+window.postMessage({
+  message: "check"
+}, "*");
+ +

הקוד רק יוצר משתנים x ו- y באמצעות window.eval() ו-eval(), ואז רושם את ערכיהם ליומן, ואז שולח הודעה לדף.

+ +

בהתקבל ההודעה, תסריט הדף רושם ליומן את אותם המשתנים:

+ +
window.addEventListener("message", function(event) {
+  if (event.source === window && event.data && event.data.message === "check") {
+    console.log(`In page script, window.x: ${window.x}`);
+    console.log(`In page script, window.y: ${window.y}`);
+  }
+});
+ +

בכרום, מופק פלט כזה:

+ +
In content script, window.x: 1
+In content script, window.y: 2
+In page script, window.x: undefined
+In page script, window.y: undefined
+ +

בפיירפוקס מופק הפלט הבא:

+ +
In content script, window.x: undefined
+In content script, window.y: 2
+In page script, window.x: 1
+In page script, window.y: undefined
+ +

אותו הדבר תקף עבור setTimeout(), setInterval(), ו- Function().

+ +
+

בעת הרצת קוד בהקשר של דף, יש להיזהר מאוד. סביבת הדף נשלטת על ידי דפי רשת בעלי פוטנציאל לזדוניות, דבר היכול להגדיר מחדש אובייקטים איתם את/ה מתקשר/ת להתנהג בדרכים לא צפויות.

+ +
// page.js redefines console.log
+
+var original = console.log;
+
+console.log = function() {
+  original(true);
+}
+
+ + +
// content-script.js calls the redefined version
+
+window.eval('console.log(false)');
+
+
diff --git a/files/he/mozilla/add-ons/webextensions/index.html b/files/he/mozilla/add-ons/webextensions/index.html new file mode 100644 index 0000000000..221ec714ca --- /dev/null +++ b/files/he/mozilla/add-ons/webextensions/index.html @@ -0,0 +1,147 @@ +--- +title: הרחבות לדפדפנים +slug: Mozilla/Add-ons/WebExtensions +tags: + - הרחבות + - נחיתה + - תוספים +translation_of: Mozilla/Add-ons/WebExtensions +--- +
{{AddonSidebar}}
+ +

הרחבות יכולות להרחיב ולשנות את יכולות הדפדפן. הרחבות של Firefox נבנות על-ידי WebExtensions API, מערכת חוצת-דפדפנים לפיתוח הרחבות.המערכת תואמת ל- extension API הנתמך על-ידי Google Chrome ו- Opera ו- W3C Draft Community Group במידה נרחבת.

+ +

הרחבות הנכתבות לדפדפנים אלה ירוצו ברוב המקרים ב- Firefox או ב-Microsoft Edge עם שינויים מועטים בלבד. ה- API גם תואם באופן מלא multiprocess Firefox.

+ +

אם יש לך רעיונות או שאלות, או צורך בעזרה בהעברת תוספים ישנים ל-WebExtensions APIs, ניתן ליצור עימנו קשר ב-רשימת התפוצה של dev-addons או ב- #webextensions ב- IRC.

+ +
+
+

תחילת עבודה

+ + + +

מושגים

+ + + +

ממשק משתמש

+ + + +

איך לעשות

+ + + +
    +
+ +

הסבה

+ + + +

תרשים עבודה של Firefox

+ + +
+ +
+

רשימת מקורות

+ +

JavaScript APIs

+ + + +
{{ListSubpages("/en-US/docs/Mozilla/Add-ons/WebExtensions/API")}}
+ +

מפתחות מניפסט

+ + + +
{{ListSubpages("/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json")}}
+
+
+ + diff --git a/files/he/mozilla/add-ons/webextensions/manifest.json/background/index.html b/files/he/mozilla/add-ons/webextensions/manifest.json/background/index.html new file mode 100644 index 0000000000..cbd429b6f9 --- /dev/null +++ b/files/he/mozilla/add-ons/webextensions/manifest.json/background/index.html @@ -0,0 +1,116 @@ +--- +title: background +slug: Mozilla/Add-ons/WebExtensions/manifest.json/background +tags: + - Manifest + - WebExtensions + - הרחבות + - הרחבות רשת + - עיון + - תוספים +translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/background +--- +
{{AddonSidebar}}
+ + + + + + + + + + + + + + + + +
טיפוסObject
חובהלא
דוגמה +
+"background": {
+  "scripts": ["background.js"]
+}
+
+ +

השתמשו במפתח background כדי לכלול תסריט רקע אחד או יותר, עם אפשרות לדף רקע בהרחבתכם.

+ +

תסריטי רקע הם המקום לשים קוד שצריך לתחזק מצב לטווח ארוך, או לבצע פעולות לטווח ארוך, ללא תלות בזמן החיים של דף מסוים מהרשת או חלון דפדפן.

+ +

תסריטי רקע נטענים מיד כשההרחבה נטענת והם נשארים טעונים עד אשר ההרחבה מושבתת או מבוטלת, אלא אם persistent מקבל את הערך false. תוכלו להשתמש בכל אחד ממשקי פיתוח היישומים של הרחבות הרשת בתסריט, כל עוד ביקשתם את ההרשאות הנחוצות.

+ +

ראו גם את הקטע "תסריטי רקע" ב- אנטומיה של הרחבה לפרטים נוספים.

+ +

המפתח background הוא אובייקט שעשויות להיות לו שתי תכונות, ושתיהן אופציונליות:

+ + + + + + + + + + + + +
scripts +

מערך (Array) של מחרוזות ( Strings), שכל אחת מהן היא מסלול למקור בג'אווה-סקריפט. המסלול יחסי לקובץ manifest.json עצמו. אלה התסריטים שיבוצעו בדף הרקע של ההרחבה.

+ +

התסריט משתף את אותו הקשר גלובלי  window.

+ +

התסריטים נטענים על פי הסדר בו הם מופיעים במערך.

+ +

אם תציינו ערך עבור scripts, דף ריק יווצר בו יורץ התסריט.

+ +
+

לתשומת לבך: אם ברצונך להביא תסריט ממיקום מרוחק עם התגית <script>  (לדוגמה,. <script src = "https://code.jquery.com/jquery-1.7.1.min.js">), יהא עליך לשנות גם את המפתח content_security_policy בקובץ manifest.json של ההרחבה שלך.

+
+ +
+

לתשומת לבך: בגרסאות פיירפוקס שקדמו לגרסה 50, כשהדיבאגר היה פתוח, תסריטים לא תמיד נטענו על פי הסדר הניתן במערך . כדי לעקוף באג זה, ניתן להשתמש בתכונה page ולכלול תסריטי רקע מהדף באמצעות תגיות  <script>. באג זה תוקן בפיירפוקס 50. מנקודה זו ואילך,  תסריטים נטענים תמיד על פי הסדר הנתון במערך.

+
+
page +

אם יש לך צורך בתוכן כלשהו בדף, ניתן להגדיר דף משלך באמצעות התכונה  page, שהיא מחרוזת ( String ), המייצגת מסלול, יחסי לקובץ manifest.json, למסמך HTML הכלול בחבילת ההרחבה שלך.

+ +

אם נעשה שימוש בתכונה זו, לא יהיה ניתן לציין תסריטי רקע באמצעות scripts, אך יהיה ניתן לכלול תסריטים משלך מהדף, בדיוק כשם שזה נעשה בדף רגיל מהרשת.

+
+ +

המפתח background יכול לכלול גם את התכונה האופציונלית הבאה:

+ + + + + + + + +
persistent +

ערך בוליאני( Boolean ).

+ +
    +
  • true מציין כי דף הרקע נועד להישמר בזכרון מהרגע שההרחבה נטענה או שהדפדפן הופעל  עד שההרחבה מבוטלת או מושבתת, או שהדפדפן נסגר (כלומר, דף הרקע תמידי).
  • +
  • false מציין כי דף הרקע עשוי להיות מוסר מהזיכרון כשלא פעיל ולהיווצר מחדש במידת הצורך. דפי רקע כאלה קרויים לפעמים דפי אירוע כי הם נטענים לזיכרון כדי לאפשר לדף הרקע לטפל באירועים להם הוא הוסיף מאזינים. רישום המאזיננים הוא תמידי כאשר הדף מוסר מהזיכרון, אך ערכים אחרים אינם ץמידי. אם תרצו לשמור מידע תמידית בדף אירועים , תוכלו להשתמש ב  ממשק הפיתוח storage.
  • +
+
+ +

דוגמה

+ +
  "background": {
+    "scripts": ["jquery.js", "my-background.js"]
+  }
+ +

טוען שני תסריט רקע.

+ +
  "background": {
+    "page": "my-background.html"
+  }
+ +

תואן דף רקע מותאם אישית.

+ +

תאימות דפדפנים

+ + + +

{{Compat("webextensions.manifest.background", 10)}}

diff --git a/files/he/mozilla/add-ons/webextensions/manifest.json/index.html b/files/he/mozilla/add-ons/webextensions/manifest.json/index.html new file mode 100644 index 0000000000..13e7d0f8f8 --- /dev/null +++ b/files/he/mozilla/add-ons/webextensions/manifest.json/index.html @@ -0,0 +1,125 @@ +--- +title: manifest.json +slug: Mozilla/Add-ons/WebExtensions/manifest.json +tags: + - Add-ons + - Extensions + - NeedsTranslation + - Overview + - TopicStub + - WebExtensions + - manifest.json +translation_of: Mozilla/Add-ons/WebExtensions/manifest.json +--- +

{{AddonSidebar}}

+ +
+

This article describes manifest.json for web extensions. If you are looking for information about the manifest.json in PWAs, check out the Web App Manifest article.

+
+ +

The manifest.json file is the only file that every extension using WebExtension APIs must contain.

+ +

Using manifest.json, you specify basic metadata about your extension such as the name and version, and can also specify aspects of your extension's functionality, such as background scripts, content scripts, and browser actions.

+ +

It is a JSON-formatted file, with one exception: it is allowed to contain "//"-style comments.

+ +

manifest.json keys are listed below:

+ +
{{ListSubpages("/en-US/Add-ons/WebExtensions/manifest.json")}}
+ +

"manifest_version", "version", and "name" are the only mandatory keys. "default_locale" must be present if the "_locales" directory is present and must be absent otherwise. "browser_specific_settings" is not supported in Google Chrome.

+ +

You can access your extension's manifest from the extension's JavaScript using the {{WebExtAPIRef("runtime.getManifest()")}} function:

+ +
browser.runtime.getManifest().version;
+ +

Example

+ +

The block below contains shows the basic syntax for some common manifest keys. Note that it is not intended to be used as a copy-paste-ready example: which keys you need will depend on the extension you are developing. For complete example extensions, see Example extensions.

+ +
{
+  "browser_specific_settings": {
+    "gecko": {
+      "id": "addon@example.com",
+      "strict_min_version": "42.0"
+    }
+  },
+
+  "background": {
+    "scripts": ["jquery.js", "my-background.js"],
+    "page": "my-background.html"
+  },
+
+  "browser_action": {
+    "default_icon": {
+      "19": "button/geo-19.png",
+      "38": "button/geo-38.png"
+    },
+    "default_title": "Whereami?",
+    "default_popup": "popup/geo.html"
+  },
+
+  "commands": {
+    "toggle-feature": {
+      "suggested_key": {
+        "default": "Ctrl+Shift+Y",
+        "linux": "Ctrl+Shift+U"
+      },
+      "description": "Send a 'toggle-feature' event"
+    }
+  },
+
+  "content_security_policy": "script-src 'self' https://example.com; object-src 'self'",
+
+  "content_scripts": [
+    {
+      "exclude_matches": ["*://developer.mozilla.org/*"],
+      "matches": ["*://*.mozilla.org/*"],
+      "js": ["borderify.js"]
+    }
+  ],
+
+  "default_locale": "en",
+
+  "description": "...",
+
+  "icons": {
+    "48": "icon.png",
+    "96": "icon@2x.png"
+  },
+
+  "manifest_version": 2,
+
+  "name": "...",
+
+  "page_action": {
+    "default_icon": {
+      "19": "button/geo-19.png",
+      "38": "button/geo-38.png"
+    },
+    "default_title": "Whereami?",
+    "default_popup": "popup/geo.html"
+  },
+
+  "permissions": ["webNavigation"],
+
+  "version": "0.1",
+
+  "user_scripts": {
+    "api_script": "apiscript.js",
+  },
+
+  "web_accessible_resources": ["images/my-image.png"]
+}
+ +

Browser compatibility

+ +

For a full overview of all manifest keys and their sub-keys, see the full manifest.json browser compatibility table.

+ + + +

{{Compat("webextensions.manifest")}}

+ +

See also

+ +

{{WebExtAPIRef("permissions")}} JavaScript API

diff --git "a/files/he/mozilla/add-ons/webextensions/manifest.json/\327\224\327\250\327\251\327\220\327\225\327\252/index.html" "b/files/he/mozilla/add-ons/webextensions/manifest.json/\327\224\327\250\327\251\327\220\327\225\327\252/index.html" new file mode 100644 index 0000000000..9221f0cf8c --- /dev/null +++ "b/files/he/mozilla/add-ons/webextensions/manifest.json/\327\224\327\250\327\251\327\220\327\225\327\252/index.html" @@ -0,0 +1,198 @@ +--- +title: הרשאות +slug: Mozilla/Add-ons/WebExtensions/manifest.json/הרשאות +tags: + - manifest.json + - הפניה + - הרחבות + - הרחבות רשת + - הרשאות + - תוספים +translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/permissions +--- +

{{AddonSidebar}}

+ + + + + + + + + + + + + + + + +
טיפוסArray
חובהלא
דוגמה +
+"permissions": [
+  "*://developer.mozilla.org/*",
+  "webRequest"
+]
+
+ +

השתמשו במפתח permissions לבקש כוחות מיוחדים עבור ההרחבה שלכם. מפתח זה הינו מערך של מחרוזות, וכל אחת ממחרוזות אלו היא בקשת הרשאה.

+ +

אם תבקשו הרשאות באמצעות מפתח זה, אזי הדפדפן עשוי  לדווח למשתמש/ת בעת ההתקנה שההרבה מבקשת פריבילגיות מסויימות, ולבקש ממנו/ה לאשר כי  ישמח/תשמח להעניק פריבילגיות אלו. הדפדפן עשוי גם להתיר למשתמש/ץ לבדוק פריבילגיות ההרחבה אחרי ההתקנה. כשם שהבקשה להעניק פריבילגיות עשויה להשפיע על נכונות המשתמש/ת להתקין את ההרחבה, בקשת פריבילגיות שווה הפעלה זהירה של שיקול דעת.  לדוגמה, אם תרצו להימנע מלבקש הרשאות לא נחוצות  ותרצו לספק מידע עודות הסיבה לבקשת הרשאות בתיאור המוצר של ההרחבה שלכם. מידע נוסף על העניינים שיש לקחת בחשבון תוכלו למצוא במאמר  Request the right permissions.

+ +

למידע נוסף כיצד לבחון ולצפות בבקשת הרשאות ראו Test permission requests  באתר Extension Workshop site.

+ +

המפתח יכול להכיל שלושה סוגי הרשאות:

+ + + +

הרשאות מארח

+ +

הרשאות מארח מפורטות ב- match patterns, וכל תבנית מזהה קבוצה של כתובות  URLs עבורן ההרחבה מבקשת פריבילגיות נוספות. לדוגמה, בקשת מארח יכולה להיות  "*://developer.mozilla.org/*".

+ +

פריבילגיות נוספות כוללות:

+ + + +

בפירפוקס, מגירסה 56 ואילך, הרחבות מקבלות אוטומטית הרשאות מארח  עבור המקור של עצמן, שהוא בצורה:

+ +
moz-extension://60a20a9b-1ad4-af49-9b6c-c64c98c37920/
+ +

כש-  60a20a9b-1ad4-af49-9b6c-c64c98c37920 הוא המזהה הפנימי של ההרחבה. ההרחבה יכולה לקבל את ה- URL תכנותית על ידי קריאה ל- extension.getURL():

+ +
browser.extension.getURL("");
+// moz-extension://60a20a9b-1ad4-af49-9b6c-c64c98c37920/
+
+ +

הרשאות ממשק פיתוח יישומים

+ +

הרשאות ממשק פיתוח היישומים מפורטות כמילות מפתח, וכל מילת מפתח מהווה שם של  WebExtension API שההרחבה מעוניינת להשתמש בו.

+ +

כעת זמינות מילות המפתח הבאות:

+ + + +

ברוב המקרים ההרשאה רק מעניקה גישה לממשק פיתוח היישומים, עם יוצאי הדופן הבאים:

+ + + +

הרשאת activeTab

+ +

הרשאה זו מצויינת כ- "activeTab". אם להרחבה יש הרשאה זו , אזי בעת תקשורת בין משתמש/ת להרחבה, מוענקות להרחבה פריבילגיות  נוספות ללשונית הפעילה בלבד.

+ +

"תקשורת עם המשתמש" כוללת:

+ + + +

הפריבילגיות הנוספות הן:

+ + + +

הכוונה בהרשאה זו היא לאפשר להרחבות להגשים מקרה שימוש נפוץ, ללא הצורך לתת להן הרשאות בעלות כוח רב מדי. הרשאות רבוטת יהיו מעונינות "לעשות משהו לדף הנוכחי כאשר המשתמש/ת מבקש/ת". לדוגמה, קחו בחשבון הרחבה המבקשת להריץ תסריט בדף הנוכחי כאשר המשתמש/ת מקישה על פעולת דפדפן. אם ההרשאה  activeTab לא הייתה קיימת, ההרחבה הייתה צריכה לבקש את ההרשאת המארח   <all_urls>. אבל זה נותן להרחבה יותר כוח ממה שדרוש לה:  היא הייתה יכולה כעת לבצע תסריטים בכל לשונית, בכל עת שתרצה, במקום רק בלשונית הפעילה ורק בתגובה לפעולת משתמש/ת.

+ +

שימו לב כי תוכלו לקבל גישה רק ללשונית/מידע שכבר שם, כאשר ההתקשרות מצד המשתמש/ת התקיימה (למשל. ההקשה). כאשר הלשונית הפעילה מנווטת למקום אחר, למשל עקב סיום טעינה או אירוע אחר כלשהו, ההרשאה אינה מעניקה לך יותר גישה ללשונית.

+ +

בדרך כלל הלשונית המקבלת את הרשאת activeTab היא רק הלשונית הפעילה באותו רגע, פרט למקרה אחד. ממשק היישומים menus מאפשר להרחבה ליצור פריט תפריט המוצג כאשר המשתמש/ת מקיש/ה הקשת הקשר בלשונית  (כלומר, על הרכיב בפס הלשוניות המשאפשר למשתמש/ת לעבור מלשונית ללשונית). אם המשתמש/ת מקיש/ה על פריט כזה, אזי הרשאת  activeTab מוענקת ללשונית שהוקש עליה, אף אם זו אינה הלשונית הפעילה (נכון לפיירפוקס 63, {{bug(1446956)}}).

+ +

גישה ללוח הגזירים

+ +

קיימות שתי הרשאות המאפשרות להרחבה  לתקשר עם לוח הגזירים:

+ + + +

ראו Interact with the clipboard לכל הפרטים אודות הדבר.

+ +

אחסון ללא הגבלה

+ +

הרשאת unlimitedStorage:

+ + + +

דוגמה

+ +
 "permissions": ["*://developer.mozilla.org/*"]
+ +

לבקשת הרשאה בעלת פריבילגיה  לדפים תחת developer.mozilla.org.

+ +
  "permissions": ["tabs"]
+ +

לבקשת גישה לחלקים בעלי פריבילגיה של ממשק הפיתוח  tabs.

+ +
  "permissions": ["*://developer.mozilla.org/*", "tabs"]
+ +

לבקשת שתי ההרשאות שלעיל.

+ +

תאימות דפדפנים

+ + + +

{{Compat("webextensions.manifest.permissions")}}

diff --git a/files/he/mozilla/add-ons/webextensions/modify_a_web_page/index.html b/files/he/mozilla/add-ons/webextensions/modify_a_web_page/index.html new file mode 100644 index 0000000000..8ad3ab8cc5 --- /dev/null +++ b/files/he/mozilla/add-ons/webextensions/modify_a_web_page/index.html @@ -0,0 +1,252 @@ +--- +title: שינוי דפים מהרשת +slug: Mozilla/Add-ons/WebExtensions/Modify_a_web_page +translation_of: Mozilla/Add-ons/WebExtensions/Modify_a_web_page +--- +
{{AddonSidebar}}
+ +

אחד השימושים הנפוצים להרחגה הוא לשנות דף מהרשת. לדוגמה,  הרחבה עשויה לרצות שלנות את הסגנון שבשימוש הדף , להסתיר צמתי DOM מסויימים, או להחדיר צמתי DOM נוןספים לדף.

+ +

קיימות שתי דרכים לעשות זאת עם ממשקי פיתוח הרחבות הרשת:

+ + + +

בכל דרך, תסריטים אלה קרויים תסריטי תוכן, והם שונים מתסריטים אחרים שההרחבה עשויה מהם:

+ + + +

במאמר זה נתבונן בשתי השיטות של טעינת תסריט.

+ +

שינויים בדפים התואמים תבנית URL

+ +

קודם כל, צרו תיקייה חדשה בשם "modify-page". בתיקייה זו, צרו קובץ בשם   "manifest.json", המכיל את התוכן הבא:

+ +
{
+
+  "manifest_version": 2,
+  "name": "modify-page",
+  "version": "1.0",
+
+  "content_scripts": [
+    {
+      "matches": ["https://developer.mozilla.org/*"],
+      "js": ["page-eater.js"]
+    }
+  ]
+
+}
+ +

המפתח content_scripts הוא הדרך לטעון תסריטים לתוך דפים התואמים תבניות  URL  במקרה זה, content_scripts מורה לדפדפן לטעון תסריט בשם   "page-eater.js" לתוך כל הדפים תחת https://developer.mozilla.org/.

+ +
+

מאחר שהתכונה "js" של  content_scripts היא מערך, תוכלו להשתמש בה כדי להחדיר יותר מתסריט אחד לתוך דפים תואמים . אם תעשו זאת דף יחלוק את אותו התחום, כשם שתסריטים מרובים הנטענים על ידי דף, והם ייטענו בסדר שנרשמו בתוך המערך.

+
+ +
+

למפתח content_scripts יש גם תכונת "css" בה תוכלו להשתמש כדי להחסיר דפי סגנונות המקודדים ב-CSS

+
+ +

כעת, צרו קובץ בשם "page-eater.js" בתוך התיקייה "modify-page" , ושימו בו את התוכן הבא:

+ +
document.body.textContent = "";
+
+var header = document.createElement('h1');
+header.textContent = "This page has been eaten";
+document.body.appendChild(header);
+ +

כעת iהתקינו את ההרחבה, ובקרו בדף https://developer.mozilla.org:/

+ +

{{EmbedYouTube("lxf2Tkg6U1M")}}

+ +
+

שימו לב כי למרות שבסרטון מוצג תסריט תוכן הפועל ב- addons.mozilla.org, תסריטי תוכן לעת עתה חסומים באתר זה.

+
+ +

שינוי דפים תכנותית

+ +

מה אם תרצו לאכול דפים, אבל רק כשהמשתמש/ת מבקש/ת זאת? הבה נעדכן את הדוגמה הבאה כך שנחדיר תסריט תוכן כאשר משתמש/ת מקיש/ה על פריט מתפריט ההקשר.

+ +

תחילה, עדכנו את  "manifest.json" כך שיכיל את התוכן הבא:

+ +
{
+
+  "manifest_version": 2,
+  "name": "modify-page",
+  "version": "1.0",
+
+  "permissions": [
+    "activeTab",
+    "contextMenus"
+  ],
+
+  "background": {
+    "scripts": ["background.js"]
+  }
+
+}
+ +

כאן, הוצאנו את המפתח content_scripts, והוספנו שני מפתחות חדשים:

+ + + +

Let's create this file. Create a new file called "background.js" in the "modify-page" directory, and give it the following contents:

+ +
browser.contextMenus.create({
+  id: "eat-page",
+  title: "Eat this page"
+});
+
+browser.contextMenus.onClicked.addListener(function(info, tab) {
+  if (info.menuItemId == "eat-page") {
+    browser.tabs.executeScript({
+      file: "page-eater.js"
+    });
+  }
+});
+
+ +

In this script we're creating a context menu item, giving it a specific id and title (the text to be displayed in the context menu). Then we set up an event listener so that when the user clicks a context menu item, we check to see if it is our eat-page item. If it is, we inject "page-eater.js" into the current tab using the tabs.executeScript() API. This API optionally takes a tab ID as an argument: we've omitted the tab ID, which means that the script is injected into the currently active tab.

+ +

At this point the extension should look like this:

+ +
modify-page/
+    background.js
+    manifest.json
+    page-eater.js
+ +

Now reload the extension, open a page (any page, this time) activate the context menu, and select "Eat this page":

+ +

{{EmbedYouTube("zX4Bcv8VctA")}}

+ +
+

Note that although this video shows the content script working in addons.mozilla.org, content scripts are currently blocked for this site.

+
+ +

Messaging

+ +

Content scripts and background scripts can't directly access each other's state. However, they can communicate by sending messages. One end sets up a message listener, and the other end can then send it a message. The following table summarises the APIs involved on each side:

+ + + + + + + + + + + + + + + + + + + +
In content scriptIn background script
Send a messagebrowser.runtime.sendMessage()browser.tabs.sendMessage()
Receive a messagebrowser.runtime.onMessagebrowser.runtime.onMessage
+ +
+

In addition to this method of communication, which sends one-off messages, you can also use a connection-based approach to exchange messages. For advice on choosing between the options, see Choosing between one-off messages and connection-based messaging.

+
+ +

Let's update our example to show how to send a message from the background script.

+ +

First, edit "background.js" so that it has these contents:

+ +
browser.contextMenus.create({
+  id: "eat-page",
+  title: "Eat this page"
+});
+
+function messageTab(tabs) {
+  browser.tabs.sendMessage(tabs[0].id, {
+    replacement: "Message from the extension!"
+  });
+}
+
+function onExecuted(result) {
+    var querying = browser.tabs.query({
+        active: true,
+        currentWindow: true
+    });
+    querying.then(messageTab);
+}
+
+browser.contextMenus.onClicked.addListener(function(info, tab) {
+  if (info.menuItemId == "eat-page") {
+    let executing = browser.tabs.executeScript({
+      file: "page-eater.js"
+    });
+    executing.then(onExecuted);
+  }
+});
+
+ +

Now, after injecting "page-eater.js", we use tabs.query() to get the currently active tab, and then use tabs.sendMessage() to send a message to the content scripts loaded into that tab. The message has the payload {replacement: "Message from the extension!"}.

+ +

Next, update "page-eater.js" like this:

+ +
function eatPageReceiver(request, sender, sendResponse) {
+  document.body.textContent = "";
+  var header = document.createElement('h1');
+  header.textContent = request.replacement;
+  document.body.appendChild(header);
+}
+browser.runtime.onMessage.addListener(eatPageReceiver);
+
+ +

Now instead of just eating the page right away, the content script listens for a message using runtime.onMessage. When a message arrives, the content script runs essentially the same code as before, except that the replacement text is taken from request.replacement.

+ +

Since tabs.executeScript() is an asynchronous function, and to ensure we send message only after listener has been added in "page-eater.js", we use onExecuted which will be called after "page-eater.js" executed.

+ +
+

Press Ctrl+Shift+J (or Cmd+Shift+J on a Mac) OR web-ext run --bc to open Browser Console to view console.log in background script. Alternatively use Add-on Debugger  which allows you set breakpoint. There is currently no way to start Add-on Debugger directly from web-ext.

+
+ +

If we want send messages back from the content script to the background page,  we would use runtime.sendMessage() instead of tabs.sendMessage(), e.g.:

+ +
browser.runtime.sendMessage({
+    title: "from page-eater.js"
+});
+ +
+

These examples all inject JavaScript; you can also inject CSS programmatically using the tabs.insertCSS() function.

+
+ +

Learn more

+ + diff --git a/files/he/mozilla/add-ons/webextensions/user_interface/browser_action/index.html b/files/he/mozilla/add-ons/webextensions/user_interface/browser_action/index.html new file mode 100644 index 0000000000..d3ae50e9d9 --- /dev/null +++ b/files/he/mozilla/add-ons/webextensions/user_interface/browser_action/index.html @@ -0,0 +1,51 @@ +--- +title: כפתור בסרגל הכלים +slug: Mozilla/Add-ons/WebExtensions/user_interface/Browser_action +tags: + - WebExtension + - הרחבת רשת +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Browser_action +--- +
{{AddonSidebar}}
+ +

קרוי בשימוש נפוץ פכולת דפדפן, אפשרות זו של ממשק המשתמש  היא כפתור המתוסף לסרגל הכלים של הדפדפן. המשתמשים מקישים על הכפתור כדי לתקשר עם ההרחבה שלך.
+

+ +

הכפתור בסרגל הכלים (פעולת דפדפן) דומה לכפתור של שur, הכתובת (פעולת דף). להבדלים ולהדרכה מתי להשתמש במה,ראו Page actions and browser actions.

+ +

Specifying the browser action

+ +

You define the browser action's properties using the browser_action key in manifest.json:

+ +
"browser_action": {
+  "default_icon": {
+    "19": "button/geo-19.png",
+    "38": "button/geo-38.png"
+  },
+  "default_title": "Whereami?"
+}
+ +

The only mandatory key is default_icon.

+ +

There are two ways to specify a browser action: with or without a popup. If you don't specify a popup, when the user clicks the button an event is dispatched to the extension, which the extension listens for using browserAction.onClicked:

+ +
browser.browserAction.onClicked.addListener(handleClick);
+ +

If you specify a popup, the click event is not dispatched: instead, the popup is shown when the user clicks the button. The user is able to interact with the popup and it closes automatically when the user clicks outside it. See the Popup article for more details on creating and managing popups.

+ +

Note that your extension can have only one browser action.

+ +

You can change many of the browser action properties programmatically using the browserAction API.

+ +

Icons

+ +

For details on how to create icons to use with your browser action, see Iconography in the Photon Design System documentation.

+ +

Examples

+ +

The webextensions-examples repository on GitHub contains two examples of extensions that implement browser actions:

+ + diff --git a/files/he/mozilla/add-ons/webextensions/user_interface/index.html b/files/he/mozilla/add-ons/webextensions/user_interface/index.html new file mode 100644 index 0000000000..78b988a523 --- /dev/null +++ b/files/he/mozilla/add-ons/webextensions/user_interface/index.html @@ -0,0 +1,97 @@ +--- +title: User interface +slug: Mozilla/Add-ons/WebExtensions/user_interface +tags: + - Landing + - NeedsTranslation + - TopicStub + - User Interface + - WebExtensions +translation_of: Mozilla/Add-ons/WebExtensions/user_interface +--- +
{{AddonSidebar}}
+ +

Extensions that use WebExtension APIs are provided with several user interface options so that their functionality can be made available to the user. A summary of those options is provided below, with a more detailed introduction to each user interface option in this section.

+ +
+

For advice on using these UI components to create a great user experience in your extension, please see the User experience best practices article.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UI optionDescriptionExample
Toolbar button (browser action)A button on the browser toolbar that dispatches an event to the extension when clicked. By default, the button is visible in all tabs.Example showing a toolbar button (browser action).
Toolbar button with a popupA popup on a button in the browser toolbar that opens when the button is clicked. The popup is defined in an HTML document that handles the user interaction.Example of the pop-up on a toolbar button
Address bar button (page action)A button on the browser address bar that dispatches an event to the extension when clicked. By default, the button is hidden in all tabs.Example showing an address bar button (page action)
Address bar button with a popupA popup on a button in the browser address bar that opens when the button is clicked. The popup is defined in an HTML document that handles the user interaction.Example of a popup on the address bar button
Context menu itemMenu items, checkboxes, and radio buttons on one or more of the browser's context menus. Also, menus can be structured by adding separators. When menu items are clicked, an event is dispatched to the extension.Example of content menu items added by a WebExtension, from the context-menu-demo example
Sidebar +

An HTML document displayed next to a web page, with the option for unique content per page. The sidebar is opened when the extension is installed, then obeys the user's sidebar visibility selection. User interaction within the sidebar is handled by its HTML document.

+
Example of a sidebar
Options pageA page that enables you to define preferences for your extension that your users can change. The user can access this page from the browser's add-ons manager.Example showing the options page content added in the favorite colors example.
Extension pageUse web pages included in your extension to provide forms, help, or any other content required, within windows or tabs.Example of a simple bundled page displayed as a detached panel.
NotificationTransient notifications displayed to the user through the underlying operating system's notifications mechanism. Dispatches an event to the extension when the user clicks a notification, or when a notification closes (either automatically or at the user's request).Example of an extension triggered system notification
Address bar suggestionOffer custom address bar suggestions when the user enters a keyword.Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions.
Developer tools panelA tab with an associated HTML document that displays in the browser's developer tools.Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions.
+ +

The following how-to guides provide step-by-step guidance to creating some of these user interface options:

+ + diff --git a/files/he/mozilla/add-ons/webextensions/what_are_webextensions/index.html b/files/he/mozilla/add-ons/webextensions/what_are_webextensions/index.html new file mode 100644 index 0000000000..2dbe632f44 --- /dev/null +++ b/files/he/mozilla/add-ons/webextensions/what_are_webextensions/index.html @@ -0,0 +1,59 @@ +--- +title: מהן הרחבות? +slug: Mozilla/Add-ons/WebExtensions/What_are_WebExtensions +tags: + - הרחבות + - הרחבות רשת +translation_of: Mozilla/Add-ons/WebExtensions/What_are_WebExtensions +--- +
{{AddonSidebar}}
+ +

הרחבה מוסיפה תכונות ותפקודים לדפדפן. היא נוצרת באמצעות טכנולוגיות מוכרות מבוססות רשת—HTML, CSS, וג'אווהסקריפט. החא משתמשת באותם ממשקי פיתוח לרשת כמו ג'אווה סקריפט  בדף רשת, אך בנוסף ההרחבה ניגשת לקבוצת ממשקי פיתוח בג'אווהסקריפט משלה. . זאת אומרת שניתן לעשות הרבה יותר בהרחבה מאשר עם קוד בדף הרשת. . הנה לפניכם מספר דוגמאות של דברים שניתן לעשות:

+ +

שדרוג או השלמה של אתר: השתמשו בתוסף למסור תכונות פנים דפדפן או מידע מתוך האתר שלכם. הרשו למשתמשים לאסוף פרטים מתוך דפים שהם מבקרים בהם כדי לשפר את השירות שאתם מציעים.

+ +

+ +

Examples: Amazon Assistant for Firefox, OneNote Web Clipper, and Grammarly for Firefox

+ +

לתת למשתמשים להציג את האישיות שלהם: הרחבות דפדפן יכולות לטפל בתוכן של דפים ברשת; לדוגמא, לתת למשתמשים להוסיף את הלוגו או התמונה המועדפים עליהם כרקע לכל דף שהם מבקרים בו. הרחבות יכולות גם לאפשר למשתמשים לעדכן את המראה של ממשק משתמש פיירפוקס, באותה דרך שמאפשרים זאת  תוסף ערכת נושא  עצמאיים.

+ +

+ +

לדוגמא:: MyWeb New Tab, Tabliss, ו-VivaldiFox

+ +

להוסיף או להסיר תוכן מדפים ברשת: ייתכן ותרצו לעזור למשתמשים לחסום פרסומות פולשניותמהדפים ברשת , לספק גישה למדריך טיולים בכל עת בה ארץ או עיר מוזכרים בדף ברשת, או לעצב מחדש תוכן עמוד כדי להציע חוויית קריאה עקבית . עם היכולת לגשת ולעדכן הן את ה-HTML והן את ה CSS של הדף, הרחבות יכולות לאפשר למשתמשים לראות את הרשת כפי שירצו.

+ +

+ +

דוגמאות: uBlock Origin, Reader, ו-Toolbox for Google Play Store™

+ +

להוסיף כלים ותכונות דפדפן חדשים: הוסיפו תכונות חדשות ללוח מטלות, או צרו תמונות קוד QR מכתובות  URL, קישורים לאינטרנט, או טקסט דף. עם אפשרויות  UI גמישות והכוח של  ממשקי פיתוח של הרחבות רשת תוכלו להוסיף בקלות  תכונות חדשות לדפדפן . כמו כן, תוכלו לשדרג כממעט עכל תכונת אתר אינטרנט או תפקודו, הוא לא חייב להיות האתר שלכם.

+ +

+ +

דוגמאות: QR Code Image Generator, Swimlanes for Trello, ו-Tomato Clock

+ +

משחקים: הציעו משחקי מחשב מסורתיים עם תכונות משחק לא-מקוונות , או גלו אפשרויות משחק חדשות; לדוגמא, על ידי שילוב המשחק בגלישה היום יומית.

+ +

 

+ +

דוגמאות: Asteroids in Popup, Solitaire Card Game New Tab, ו-2048 Prime.

+ +

הוספת כלי פיתוח: ייתכן שתרצו להספק כלי פיתוח לרשת כעסק שלכם או פיתחתם טכניקה או גישה שימושיות לפיתוח לרשת שתרצו לשתף. בכל אחת מהדרכים, תוכלו לשדרג את כלי הפיתוח המובנים של פיירפוקס על ידי הוספת לשונית חדשה לסרגל הכלים של המפתח/ת.

+ +

+ +

דוגמאות: Web Developer, Web React Developer Tools, ו-aXe Developer Tools

+ +

הרחבות לפיירפוקס נבנות באמצעות ממשקי הפיתוח להרחבות רשת, מערכת לדפדפנים שוניםלפיתוח הרחבות. במידה רבה , tממשק הפיתוח תואם ל-extension API הנתמכים על ידי כרום ואופרה. הרחבות הנכתבותעבור דפדפנים אלה ירוצו ברוב המקרים על פיירפוקס will in most cases run inאו  פ Microsoft Edge בשינויים קלים בלבד. ממשק הפיתוח גם תואם באופן מלא לפיירפוקס מרובה תהליכים.

+ +

אם יש לך הצעות אושאלות, או שיש לך צורך בעזרה לעבור מתוסף מהדור הישן לממשקח הפיתוח של הרחבות הרשת , ניתון להשיגנו ב- dev-addons mailing list או בערוץ #addons ב-IRC.

+ +

מה הלאה?

+ + diff --git a/files/he/mozilla/add-ons/webextensions/your_first_webextension/index.html b/files/he/mozilla/add-ons/webextensions/your_first_webextension/index.html new file mode 100644 index 0000000000..a167a224b4 --- /dev/null +++ b/files/he/mozilla/add-ons/webextensions/your_first_webextension/index.html @@ -0,0 +1,153 @@ +--- +title: Your first extension +slug: Mozilla/Add-ons/WebExtensions/Your_first_WebExtension +tags: + - הרחבות רשת + - מדריך +translation_of: Mozilla/Add-ons/WebExtensions/Your_first_WebExtension +--- +
{{AddonSidebar}}
+ +

במאמר זה נעבור שלב שלב בפיתוח הרחבה לפיירפוקס, מההתחלה ועד הסיום. כל מה שההרחבה עושה הוא להוסיף רקע אדום לכל דף הנטען מ-"mozilla.org" או כל אחד מתת-המתחמים שלו.

+ +

קוד המקור לדוגמא זו נמצא ב- GitHub: https://github.com/mdn/webextensions-examples/tree/master/borderify.

+ +

תחילה, יש צורך בפיירפוקס מגירסה 45 ומעלה.

+ +

כתיבת ההרחבה

+ +

יש ליצור תיקייה חדשה ולנווט לתוכה. לדוגמה, משורת הפקודה\מסוף ניתן לבצע זאת כך:

+ +
mkdir borderify
+cd borderify
+ +

manifest.json

+ +

כעת, יש ליצור קובץ בשם  "manifest.json" ישירות תחת התיקייה  "borderify" . שימו בו את התוכן הבא:

+ +
{
+
+  "manifest_version": 2,
+  "name": "Borderify",
+  "version": "1.0",
+
+  "description": "Adds a red border to all webpages matching mozilla.org.",
+
+  "icons": {
+    "48": "icons/border-48.png"
+  },
+
+  "content_scripts": [
+    {
+      "matches": ["*://*.mozilla.org/*"],
+      "js": ["borderify.js"]
+    }
+  ]
+
+}
+ + + +

המפתח המעניין ביותר כאן הוא  content_scripts, המגדיר לפיירפוקס איך לטעון תסריט לתוך דפי רשת שכתובת ה-  URL שלהם תואמת תבנית מסויימת. במקרה זה, מבקשים מפיירפוקס לטעון תסריט ששמו  "borderify.js" אל תוך כל דפי ה-HTTP או HTTPS המוגשים על ידי  "mozilla.org" או כל תתי המתחמים שלו.

+ + + +
+

בכמה מצבים ייתכן ותצטרכו לציין ID עבור ההרחבה. אם יש צורך לציין מזהה תוסף, כללו את המפתח  applications ב-manifest.json והגדירו את התכונה gecko.id שלו:

+ +
"applications": {
+  "gecko": {
+    "id": "borderify@example.com"
+  }
+}
+
+ +

icons/border-48.png

+ +

ההרחבה צריכה לכלול צלמית. היא תוצג על יד רישום ההרחבה במנהל ההרחבות. הקובץ manifest.json הבטיח שתהיה לנו צלמית ב-"icons/border-48.png".

+ +

צרו את התיקייה "icons" ישירות תחת התיקייה  "borderify" . שמרו שם צלמית בשם "border-48.png".  תוכלו להשתמש  בזאת מתוך הדוגמא שלנו, הלקוחה מתוך  the Google Material Design iconset, ובשימוש תחת תנאי רשיון ה-Creative Commons Attribution-ShareAlike .

+ +

אם תבחרו לספק צלמית משלכם, היא צריכה להיות בגודל  48x48 פיקסלים. תוכלו לספק גם צלמית בגודל 96x96 פיקסלים, לצורך תצוגות ברזולוציה יותר גבוהה,  ואם תעשו זאת היא תצויין כתכונת ה-96 באובייקט icons אשר ב-manifest.json:

+ +
"icons": {
+  "48": "icons/border-48.png",
+  "96": "icons/border-96.png"
+}
+ +

לחלופין, תוכלו לספק כאן קובץ  SVG , ומימדיו ישונו בהתאם. (למרות ב: אם תשתמשו ב- SVG והצלמית תכלול טקסט, ייתכן שתרצו להשתמש בכלי   "convert to path"  של עורך ה-SVG כדי לשטח את הטקס , כך שהמידות יותאמו עם size/position עקביים.)

+ + + +

borderify.js

+ +

לסיום, צרו קובץ בשם  "borderify.js" ישירות תחת התיקייה "borderify" . שימו בו את התוכן הזה:

+ +
document.body.style.border = "5px solid red";
+ +

תסריט זה ייטעאן לתוך דפים התואמים את התבנית הנתונה  במפתח   content_scriptsב-manifest.json . לתסריט יש גישה ישירה למסמך כמו לתסקיטים הנטענים על ידי הדף עצמ .

+ + + +

לבדוק שזה עובד

+ +

תחילה, בדקו היטב שכל הקבצים נמצאים במקומות הנכונים:

+ +
borderify/
+    icons/
+        border-48.png
+    borderify.js
+    manifest.json
+ +

התקנה

+ +

פתחו את  "about:debugging" בפיירפוקס, , הקליקו  "טעינת תוספות זמניות..." and ובחרו כל קובץ שהוא  בתיקיית ההרחבה:

+ +

{{EmbedYouTube("cer9EUKegG4")}}

+ +

כעת ההרחבה תותקן, ותישאר עד שתתחילו מחדש את פיירפוקס.

+ +

לחלופין, תועלו להריץ את ההרחבה משורת הפקודה באמצעות הכלי web-ext.

+ +

בדיקה

+ +

כעת נסו לבקר בעמוד תחת  "mozilla.org", ותראו רקע אדום מסביב לדף :

+ +

{{EmbedYouTube("rxBQl2Z9IBQ")}}

+ +
+

אך אל תנסו זאת ב- addons.mozilla.org! תסריטי תוכן בשלב זה חסומים באותו מתחם.

+
+ +

ערכו ניסוי קטן. ערכו את תסריט התוכן לשנות את צבע הרקע, או עשו משהו אחר לתוכן הדף. שמרו את תוכן התסריט , ואז טענו את קבצי ההרחבה בהקלקה על קישור  ה "טעינה מחדש" ב- about:debugging. תוכלו לראות את השינויים מיד:

+ +

{{EmbedYouTube("NuajE60jfGY")}}

+ + + +

אריזה ופרסום

+ +

כדי לאפשר לאחרים להשתמש בהרחבתך, יש לארוז אותה ולשלוח למוזילה לחתימה. כדי ללמוד עוד, יש לראות "פרסום ההרחבה שלך".

+ +

מה הלאה?

+ +

כעת יש לך מושג בנושא תהליך הפיתוח של הרחבות רשת לפיירפוקס , נסה/י:

+ + diff --git a/files/he/mozilla/add-ons/webextensions/your_second_webextension/index.html b/files/he/mozilla/add-ons/webextensions/your_second_webextension/index.html new file mode 100644 index 0000000000..528daff645 --- /dev/null +++ b/files/he/mozilla/add-ons/webextensions/your_second_webextension/index.html @@ -0,0 +1,458 @@ +--- +title: ההרחבה השניה שלך +slug: Mozilla/Add-ons/WebExtensions/Your_second_WebExtension +tags: + - הרחבות רשת +translation_of: Mozilla/Add-ons/WebExtensions/Your_second_WebExtension +--- +
{{AddonSidebar}} +

אם כבר עברת את המאמר ההרחבה הראשונה שלך , כבר קיבלת מושג איך לכתוב הרחבה. במאמר זה, נכתוב הרחבה קצת יותר מורכבת המדגימה עוד קצת מממשקי הפיתוח.

+ +

ההרחבה מוסיפה כפתור חדש לסרגל הכלים של פיירפוקס. כשהמשתמש/ת מקליק/ה על הכפתור, נציג חלון קופץ המאפשר לבחור חיה. בהיבחר חיה, נחליף את תוכן הדף בחיה שנבחרה

+ +

כדי לממש זאת, אנו:

+ + + +

תוכלו לדמיין את המבנה בכללותו של ההרחבה כך:

+ +

+ +

זוהי הרחבה פשוטה, אך מציגה רבים מהקונספטים הבסיסיים של ממשק פיתוח הרחבות הרשת:

+ + + +

תוכלו למצוא complete source code for the extension on GitHub.

+ +

כדי לכתוב את ההרחבה, יש צורך בפיירפוקס מגרסא 45 או חדשה יותר.

+ +

כתיבת ההרחבה

+ +

צרו תיקייה חדשה ונווטו לתוכה:

+ +
mkdir beastify
+cd beastify
+ +

manifest.json

+ +

כעת צרו קובץ בשם "manifest.json", והכניסו בו את התוכן:

+ +
{
+
+  "manifest_version": 2,
+  "name": "Beastify",
+  "version": "1.0",
+
+  "description": "Adds a browser action icon to the toolbar. Click the button to choose a beast. The active tab's body content is then replaced with a picture of the chosen beast. See https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Examples#beastify",
+  "homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/beastify",
+  "icons": {
+    "48": "icons/beasts-48.png"
+  },
+
+  "permissions": [
+    "activeTab"
+  ],
+
+  "browser_action": {
+    "default_icon": "icons/beasts-32.png",
+    "default_title": "Beastify",
+    "default_popup": "popup/choose_beast.html"
+  },
+
+  "web_accessible_resources": [
+    "beasts/frog.jpg",
+    "beasts/turtle.jpg",
+    "beasts/snake.jpg"
+  ]
+
+}
+
+ + + +

לתשומת לבך כל המסלולים הם יחסיים ל-manifest.json עצמו.

+ +

הצלמית

+ +

להרחבה צריכה להיות צלמית. היא תהיה מוצגת על יד רישום ההרחבה ב"ניהול ההרחבות שלך" (תוכלו לפתוח אותה על ידי ביקור בכתובת "about:addons"). ה- manifest.json הבטיח שתהיה לנו צלמית לסרגל הכלים ב-  "icons/beasts-48.png".

+ +

צרו את התיקייה "icons" ושמרו שם את הצלמית בשם  "beasts-48.png".  ניתן להשתמש ב- the one from our example, הלקוחה מתוך ה-Aha-Soft’s Free Retina iconset, ונמצאת בשימוש תחת תנאי הרשיון שלה

+ +

אם תבחרו לספק צלמית משלכם, היא צריכה להיות בגודל 48x48 פיקסלים. תוכלו לספק גם צלמית בגודל 96x96 פיקסלים  , לתצוגות ברזולוציה יותר גבוהה, ואם תעשו זאת it היא תהיה מצויינת כתכונה 96 של אובייקט ה-icons ב-manifest.json:

+ +
"icons": {
+  "48": "icons/beasts-48.png",
+  "96": "icons/beasts-96.png"
+}
+ +

הכפתור בסרגל הכלים

+ +

הכפתור בסרגל הכלים צריך גם צלמית, וה- manifest.json מבטיח שתהיה לנו צלמית לכפתור בסרגל הכלים ב"icons/beasts-32.png".

+ +

שמרו צלמית בשם "beasts-32.png" בתיקייה "icons" . תוכלו להשתמש בזו מהדוגמה שלנו, הלקוחה מתוך IconBeast Lite icon set ובשימוש תחת תנאי הרשיון. שלה.

+ +

אם לא יסופק חלון קופץ, יישלח אירוע הקלקה להרחבה כאשר המשתמש/ת מקיש/ה על הכפתור. אם כן יסופק חלון קופץ, אירוע ההקלקה לא יישלח , אך במקום זאת, החלון הקופץ ייפתח . אנו רוצים חלון קופץ, אז הבה ניצור אותו כצעד הבא.

+ +

החלון הקופץ

+ +

תפקיד החלון הקופץ הוא לאפשר למשתמש/ת לבחור אחת מתוך שלוש חיות.

+ +

צרו תיקייה חדשה בשם "popup" תחת שורש ההרחבה. זה המקום שבו נשמור את הקוד עבור החלון הקופץ. החלון הקופץ יהיה מורכב משלושה קבצים:

+ + + +
mkdir popup
+cd popup
+touch choose_beast.html choose_beast.css choose_beast.js
+
+ +

choose_beast.html

+ +

קובץ ה-HTML נראה כך:

+ +
<!DOCTYPE html>
+
+<html>
+  <head>
+    <meta charset="utf-8">
+    <link rel="stylesheet" href="choose_beast.css"/>
+  </head>
+
+<body>
+  <div id="popup-content">
+    <div class="button beast">Frog</div>
+    <div class="button beast">Turtle</div>
+    <div class="button beast">Snake</div>
+    <div class="button reset">Reset</div>
+  </div>
+  <div id="error-content" class="hidden">
+    <p>Can't beastify this web page.</p><p>Try a different page.</p>
+  </div>
+  <script src="choose_beast.js"></script>
+</body>
+
+</html>
+
+ +

יש לנו אלמנט <div> עם ID  שערכו "popup-content" המכיל אלמנט עבור כל חיה שנבחרה. יש לנו עוד אלמנט <div> עם ID שערכו "error-content" וסיווגו "hidden". נשתמש בו במקרה שיש בעיה לאתחל את החלון הקופץ .

+ +

יש לשים לב לכך שאני כוללים את קובצי  ה-  CSS וה- JS מקובץ זה, בדיוק כמו דף ברשת.

+ +

choose_beast.css

+ +

ה- CSS מקבע את מידות החלון הקופץ, מבטיח ששלוש הבחירות ימלאו את החלל, ונותן להם סגנון בסיסי. הוא גם מסתיר אלמנטים עם class="hidden": כלומר שכברירת מחדל "error-content" <div> יוסתרו.

+ +
html, body {
+  width: 100px;
+}
+
+.hidden {
+  display: none;
+}
+
+.button {
+  margin: 3% auto;
+  padding: 4px;
+  text-align: center;
+  font-size: 1.5em;
+  cursor: pointer;
+}
+
+.beast:hover {
+  background-color: #CFF2F2;
+}
+
+.beast {
+  background-color: #E5F2F2;
+}
+
+.reset {
+  background-color: #FBFBC9;
+}
+
+.reset:hover {
+  background-color: #EAEA9D;
+}
+
+
+ +

choose_beast.js

+ +

הנה הג'אווהסקריפט עבור החלון הקופץ:

+ +
/**
+ * CSS to hide everything on the page,
+ * except for elements that have the "beastify-image" class.
+ */
+const hidePage = `body > :not(.beastify-image) {
+                    display: none;
+                  }`;
+
+/**
+ * Listen for clicks on the buttons, and send the appropriate message to
+ * the content script in the page.
+ */
+function listenForClicks() {
+  document.addEventListener("click", (e) => {
+
+    /**
+     * Given the name of a beast, get the URL to the corresponding image.
+     */
+    function beastNameToURL(beastName) {
+      switch (beastName) {
+        case "Frog":
+          return browser.extension.getURL("beasts/frog.jpg");
+        case "Snake":
+          return browser.extension.getURL("beasts/snake.jpg");
+        case "Turtle":
+          return browser.extension.getURL("beasts/turtle.jpg");
+      }
+    }
+
+    /**
+     * Insert the page-hiding CSS into the active tab,
+     * then get the beast URL and
+     * send a "beastify" message to the content script in the active tab.
+     */
+    function beastify(tabs) {
+      browser.tabs.insertCSS({code: hidePage}).then(() => {
+        let url = beastNameToURL(e.target.textContent);
+        browser.tabs.sendMessage(tabs[0].id, {
+          command: "beastify",
+          beastURL: url
+        });
+      });
+    }
+
+    /**
+     * Remove the page-hiding CSS from the active tab,
+     * send a "reset" message to the content script in the active tab.
+     */
+    function reset(tabs) {
+      browser.tabs.removeCSS({code: hidePage}).then(() => {
+        browser.tabs.sendMessage(tabs[0].id, {
+          command: "reset",
+        });
+      });
+    }
+
+    /**
+     * Just log the error to the console.
+     */
+    function reportError(error) {
+      console.error(`Could not beastify: ${error}`);
+    }
+
+    /**
+     * Get the active tab,
+     * then call "beastify()" or "reset()" as appropriate.
+     */
+    if (e.target.classList.contains("beast")) {
+      browser.tabs.query({active: true, currentWindow: true})
+        .then(beastify)
+        .catch(reportError);
+    }
+    else if (e.target.classList.contains("reset")) {
+      browser.tabs.query({active: true, currentWindow: true})
+        .then(reset)
+        .catch(reportError);
+    }
+  });
+}
+
+/**
+ * There was an error executing the script.
+ * Display the popup's error message, and hide the normal UI.
+ */
+function reportExecuteScriptError(error) {
+  document.querySelector("#popup-content").classList.add("hidden");
+  document.querySelector("#error-content").classList.remove("hidden");
+  console.error(`Failed to execute beastify content script: ${error.message}`);
+}
+
+/**
+ * When the popup loads, inject a content script into the active tab,
+ * and add a click handler.
+ * If we couldn't inject the script, handle the error.
+ */
+browser.tabs.executeScript({file: "/content_scripts/beastify.js"})
+.then(listenForClicks)
+.catch(reportExecuteScriptError);
+
+
+ +

המקום להתחיל פה הוא שורה 96. תסריט החלון הקופץ מבצע תסריט תוכן בלשונית הפעילה מייד כשהחלון הקופץ נטען , באמצעות ממשק הפיתוח browser.tabs.executeScript(). אם ביצוע תסריט התוכן הצליח , תסריט התוכן יישאר טעון בעמוד עד שהלשונית נסגרת או שהמשתמש/ת מנווט/ת לדף שונה.

+ +

סיבה נפוצה שהקריאה ל- browser.tabs.executeScript() עלולה להיכשל היא שלא ניתן לבתע תסריטי תוכן בכל הדפים. לדוגמא, לא ניתן לבצע אותם בדפים פריגילגיים של הדפדפן כגון "about:debugging" , ולא ניתן לבצע אותם בדפים בתוך המתחם  addons.mozilla.org. אם זה נכשל,, reportExecuteScriptError() יסתיר את ה- "popup-content" <div>, יציג את ה- "error-content" <div>, וירשום שגיאה ל-console.

+ +

אם ביצוע תסריט התוכן יצליח, נקרא ל- listenForClicks(). הוא יאזין לקליקים בחלון הקופץ..

+ + + +

הפונקציה beastify() מבצעת שלושה דברים:

+ + + +

הפונקציה reset() בהכרח מבטלת את פעולת  beastify:

+ + + +

תסריט התוכן

+ +

צרו תיקייה חדשה, תחת שורש ההרחבה, ששמה "content_scripts" וצרו קובץ חדש ששמו "beastify.js", עם התוכן הבא:

+ +
(function() {
+  /**
+   * Check and set a global guard variable.
+   * If this content script is injected into the same page again,
+   * it will do nothing next time.
+   */
+  if (window.hasRun) {
+    return;
+  }
+  window.hasRun = true;
+
+  /**
+   * Given a URL to a beast image, remove all existing beasts, then
+   * create and style an IMG node pointing to
+   * that image, then insert the node into the document.
+   */
+  function insertBeast(beastURL) {
+    removeExistingBeasts();
+    let beastImage = document.createElement("img");
+    beastImage.setAttribute("src", beastURL);
+    beastImage.style.height = "100vh";
+    beastImage.className = "beastify-image";
+    document.body.appendChild(beastImage);
+  }
+
+  /**
+   * Remove every beast from the page.
+   */
+  function removeExistingBeasts() {
+    let existingBeasts = document.querySelectorAll(".beastify-image");
+    for (let beast of existingBeasts) {
+      beast.remove();
+    }
+  }
+
+  /**
+   * Listen for messages from the background script.
+   * Call "beastify()" or "reset()".
+  */
+  browser.runtime.onMessage.addListener((message) => {
+    if (message.command === "beastify") {
+      insertBeast(message.beastURL);
+    } else if (message.command === "reset") {
+      removeExistingBeasts();
+    }
+  });
+
+})();
+
+ +

הדבר הראשון שתסריט התוכן עושה  הוא לבדוק שקיים משתנה גלובלי בשם window.hasRun: אם הוא מוגדר כאמת התסריט ירוץ מוקדם, אחרת הוא מציב ערך אמת ל0 window.hasRun וממשיך. הסיבה שאנו עושים זאת היא שכל פעם שהמשתמש/ת פותח/ת את החלון הקופץ , החלון הקופץ מבצע תסריט תוכן בלשונית הפעילה , כך שיכולים להיות לנו מופעים מרובים של התסריט רצים בלשונית יחידה. אם זה קורה, נצטרך לדאוג שרק המופע הראשון יעשה משהו באמת.

+ +

אחר כך, המקום להתחיל הוא שורה 40, בה תסריט התוכן מאזין להודעות מהחלון הקופץ, באמצעות ממשק הפיתוח  browser.runtime.onMessage. ראינו לעיל כי תסריט החלון הקופץ יכול לשלוח שני סוגי הודעות שונים : "beastify" ו-"reset".

+ + + +

החיות

+ +

לסיום, עלינו לכלול את התמונות של החיות.

+ +

צרו תיקייה חדשה ששמה "beasts", והוסיפו שלוש תמונות לתיקייה זו, אם השמות הנכונים. תוכלו להשיג את התמונות ממאגר ה-GitHub , או מפה:

+ +

+ +

לנסות את זה

+ +

תחילה, בדקו היטב שהקבצים הנכונים נמצאים במקומות הנכונים:

+ +
beastify/
+
+    beasts/
+        frog.jpg
+        snake.jpg
+        turtle.jpg
+
+    content_scripts/
+        beastify.js
+
+    icons/
+        beasts-32.png
+        beasts-48.png
+
+    popup/
+        choose_beast.css
+        choose_beast.html
+        choose_beast.js
+
+    manifest.json
+ +

החל מפיירפוקס 45, ניתן להתקין הרחבות זמנית מהדיסק.

+ +

פתחו את "about:debugging" בפיירפוקס, הקליקו  "טעינת תוספות זמניות...", ובחרו את ה- manifest.json שלכם. תצטרכו לראות כעת את צלמית ההרחבה מופיעה בסרגל הכלים של פיירפוקס

+ +

{{EmbedYouTube("sAM78GU4P34")}}

+ +

פתחו דף ברשת, ואז הקליקו על הצלמית, בחרו חיה , ורארו את הדף משתנה:

+ +

{{EmbedYouTube("YMQXyAQSiE8")}}

+ +

פיתוח משורת הפקודה

+ +

תוכלו לבצע אוטומציה של צעד ההתקנה הזמנית על ידי שימוש בכלי  web-ext. נסו את זה:

+ +
cd beastify
+web-ext run
+
diff --git "a/files/he/mozilla/add-ons/webextensions/\327\230\327\231\327\244\327\225\327\235/index.html" "b/files/he/mozilla/add-ons/webextensions/\327\230\327\231\327\244\327\225\327\235/index.html" new file mode 100644 index 0000000000..57e18c26fa --- /dev/null +++ "b/files/he/mozilla/add-ons/webextensions/\327\230\327\231\327\244\327\225\327\235/index.html" @@ -0,0 +1,57 @@ +--- +title: טיפים וטריקים +slug: Mozilla/Add-ons/WebExtensions/טיפום +tags: + - ECMAScript + - אקמהסקריפט + - הרחבות רשת + - טיפים + - טיפים וטריקים + - טריקים +translation_of: Mozilla/Add-ons/WebExtensions/Tips +--- +

{{AddonSidebar}}

+ +

עמוד זה מכיל טיפים וטריקים שוניםהאמורים להיות שימושיים לאנשים רבים המפתחים הרחבות באמצעות ממשקי הפיתוח של הרחבות רשת.

+ +

שימוש בתכונות ג'אווהסקריפט מתקדמות  מתוך ECMAScript 2015 ו-2016

+ +

פיירפוקס תומך בתכונות רבות של  ECMAScript 2015 מלוץ לקופסה. תכונות חדשות ונסיוניות אחדות, לעומת זאת, אינן זמינות לרשת או להרחבות רשת כברירת מחדל.   ,אם ברצונך להשתמש בתכונות אלו, הטוב ביותר יהיה לתרגן את הקוד שלך על ידי שימוש בכלי כמו  Babel.

+ +

יש לתת את הדעת לכך שכל דבר תחת  לשורה זו הינו מידע לא מעודכן והוצא מ-Babel 6.

+ +

Babel מספק טרנספורמציות לרוב הרחב של תכונות ES2015, ומאפשר אותן כברירת מחדל. מאחר ופיירפוקס כבר תומך באופן מלא ברובן, הטוב ביותר יהיה לקנפג את Babel להתעלם מהן. אנו ממליצים ליצור  קובץ .babelrc או מקטע babel בקובץ ה-package.json של הפרוייקט המכיל את הקוד הבא"

+ +
{
+  "env": {
+    "firefox": {
+      "sourceMaps": "inline",
+      "blacklist": [
+        "es5.properties.mutators",
+        "es6.arrowFunctions",
+        "es6.destructuring",
+        "es6.forOf",
+        "es6.parameters",
+        "es6.properties.computed",
+        "es6.properties.shorthand",
+        "es6.spec.symbols",
+        "es6.spread",
+        "es6.tailCall",
+        "es6.templateLiterals",
+        "es6.regex.sticky",
+        "es6.regex.unicode"
+      ]
+    }
+  }
+}
+
+ +

ואז, בשביל לקמפל תסרעט אינדיבידואלי, יש פשוט להריץ:

+ +
BABEL_ENV=firefox babel <filename>
+
+ +

או, כדי לקמפל כל קובץ ג'אווהסקריפט תחת התיקיה src ולמקם את הקבצים המקומפלים ב-compiled, תוך העתקה על קבצים שאינם בג'אווהסקריפט, להריץ

+ +
BABEL_ENV=firefox babel -Dd compiled src
+
diff --git a/files/he/mozilla/index.html b/files/he/mozilla/index.html new file mode 100644 index 0000000000..edba954db8 --- /dev/null +++ b/files/he/mozilla/index.html @@ -0,0 +1,10 @@ +--- +title: Mozilla +slug: Mozilla +tags: + - NeedsTranslation + - TopicStub +translation_of: Mozilla +--- +

The articles below include content about downloading and building Mozilla code. In addition, you'll find helpful articles about how the code works, how to build add-ons for Mozilla applications, and the like.

+

{{LandingPageListSubpages}}

diff --git a/files/he/mozilla/javascript_code_modules/geometry.jsm/index.html b/files/he/mozilla/javascript_code_modules/geometry.jsm/index.html new file mode 100644 index 0000000000..2e478771f2 --- /dev/null +++ b/files/he/mozilla/javascript_code_modules/geometry.jsm/index.html @@ -0,0 +1,20 @@ +--- +title: Geometry.jsm +slug: Mozilla/JavaScript_code_modules/Geometry.jsm +tags: + - Geometry + - Modules + - NeedsTranslation + - TopicStub +translation_of: Mozilla/JavaScript_code_modules/Geometry.jsm +--- +

{{ gecko_minversion_header("2.0") }}

+

The Geometry.jsm JavaScript code module provides routines for performing common geometry operations on points and rectangles. It exports two classes: Point and Rect.

+

To use these routines, you first need to import the code module into your JavaScript scope:

+
Components.utils.import("resource://gre/modules/Geometry.jsm");
+
+

Once you've imported the module, you can then use the Point and Rect classes.

+
Note: Although this module is usable from mobile, and is present in Firefox 4, it's currently not used in Firefox 4 and attempting to use it may produce unreliable results there.
+

See also

+ diff --git a/files/he/mozilla/javascript_code_modules/geometry.jsm/point/index.html b/files/he/mozilla/javascript_code_modules/geometry.jsm/point/index.html new file mode 100644 index 0000000000..54b0c6fe81 --- /dev/null +++ b/files/he/mozilla/javascript_code_modules/geometry.jsm/point/index.html @@ -0,0 +1,264 @@ +--- +title: Point +slug: Mozilla/JavaScript_code_modules/Geometry.jsm/Point +translation_of: Mozilla/JavaScript_code_modules/Geometry.jsm/Point +--- +

The Point class offers methods for performing common geometry operations on two dimensional points

+ +

Method overview

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Point add(x, y);
Point add(Point);
Point clone();
boolean equals(x, y);
Point equals(Point);
boolean isZero();
Point map(mapFunction);
Point scale(scaleFactor);
Point set(x, y);
Point set(Point);
Point subtract(x, y);
Point subtract(Point);
String toString();
+ +

Constructor

+ +

יוצר אובייקט Point חדש.

+ +
let p = new Point(x, y);
+
+ +

The new point, p, has the specified X and Y coordinates.

+ +

Methods

+ +

add()

+ +

Adds another point to this one.

+ +
Point add(
+  x,
+  y
+);
+
+Point add(
+  Point
+);
+
+ +
Parameters
+ +
+
x
+
The X coordinate of the point to add to the current point.
+
y
+
The Y coordinate of the point to add to the current point.
+
+ +
Note: You may specify another Point object instead of separate X and Y coordinates.
+ +
Return value
+ +

The value of the Point object after adding the specified value; this isn't a new object, just the same one you called the function on.

+ +

clone()

+ +

Creates and returns a copy of the Point object.

+ +
Point clone();
+
+ +
Parameters
+ +

None.

+ +
Return value
+ +

A new Point object which is a duplicate of the current object.

+ +

equals()

+ +

Determines whether another point is equal to this one.

+ +
boolean equals(
+  x,
+  y
+);
+
+boolean equals(
+  Point
+);
+
+ +
Parameters
+ +
+
x
+
The X coordinate of the point to compare to the current point.
+
y
+
The Y coordinate of the point to compare to the current point.
+
+ +
Note: You may specify another Point object instead of separate X and Y coordinates.
+ +
Return value
+ +

true if the two points are equal, otherwise false. Equality, in this context, means that both the X and Y coordinates are the same.

+ +

isZero()

+ +

Determines whether or not the point is (0, 0).

+ +
boolean isZero();
+
+ +
Parameters
+ +

None.

+ +
Return value
+ +

true if the point's X and Y coordinates are both zero; otherwise false.

+ +

map()

+ +

Calls a specified function to manipulate the values of the point's coordinates.

+ +
Point map(
+  mapFunction
+);
+
+ +
Parameters
+ +
+
mapFunction
+
The function to call to map the parameters; this function should accept one parameters: a single coordinate value. The Point object will be the value of this within the called function.
+
+ +
Return value
+ +

The value of the Point object after modifying its coordinates by calling the specified function; this isn't a new object, just the same one you called the function on.

+ +

scale()

+ +

Scales the point's coordinates by a specified factor.

+ +
Point scale(
+  scaleFactor
+);
+
+ +
Parameters
+ +
+
scaleFactor
+
The amount by which to scale the point.
+
+ +
Return value
+ +

The value of the Point object after scaling its coordinates by the specified amount; this isn't a new object, just the same one you called the function on.

+ +

set()

+ +

Sets the value of the Point object.

+ +
Point set(
+  x,
+  y
+);
+
+Point set(
+  Point
+);
+
+ +
Parameters
+ +
+
x
+
The X coordinate of the point.
+
y
+
The Y coordinate of the point.
+
+ +
Note: You may specify another Point object instead of separate X and Y coordinates.
+ +
Return value
+ +

The Point object.

+ +

subtract()

+ +

Subtracts another point from this one.

+ +
Point subtract(
+  x,
+  y
+);
+
+Point subtract(
+  Point
+);
+
+ +
Parameters
+ +
+
x
+
The X coordinate of the point to subtract from the current point.
+
y
+
The Y coordinate of the point to subtract from the current point.
+
+ +
Note: You may specify another Point object instead of separate X and Y coordinates.
+ +
Return value
+ +

The value of the Point object after subtracting the specified value; this isn't a new object, just the same one you called the function on.

+ +

toString()

+ +

Returns a string representation of the Point object.

+ +
String toString();
+
+ +
Parameters
+ +

None.

+ +
Return value
+ +

A String object representing the point, in "(x,y)" format.

diff --git a/files/he/mozilla/javascript_code_modules/index.html b/files/he/mozilla/javascript_code_modules/index.html new file mode 100644 index 0000000000..f8a4f613be --- /dev/null +++ b/files/he/mozilla/javascript_code_modules/index.html @@ -0,0 +1,147 @@ +--- +title: JavaScript code modules +slug: Mozilla/JavaScript_code_modules +tags: + - Add-ons + - Extensions + - JavaScript + - Landing + - Modules + - Mozilla + - NeedsTranslation + - TopicStub + - XPCOM +translation_of: Mozilla/JavaScript_code_modules +--- +

{{Non-standard_Header}}

+ +
+

Note: These are not the same thing as standard JavaScript modules. See {{JSxRef("Statements/export", "export")}} and {{JSxRef("Statements/import", "import")}} to learn more about how to use standard modules.

+
+ +

JavaScript code modules let multiple privileged JavaScript scopes share code. For example, a module could be used by Firefox itself as well as by extensions, in order to avoid code duplication.

+ +

General topics

+ +
+
+
+
Using JavaScript code modules
+
An introduction to how to use JavaScript code modules.
+
Components.utils.import
+
How to import a JavaScript code module.
+
Components.utils.unload
+
How to unload a JavaScript code module.
+
+
+ +
+
+
Code snippets: Modules
+
Examples of how to use code modules.
+
Mozilla Labs JS Modules
+
This page features a list of JavaScript modules, along with download links and documentation, that extension developers can use in their code.
+
+
+
+ +

Standard code modules

+ +
+
+
+
AddonManager.jsm
+
An interface to install, manage, and uninstall add-ons.
+
AddonRepository.jsm
+
Provides a search of add-ons in the repository.
+
Assert.jsm
+
Implements the CommonJS Unit Testing specification version 1.1, which provides a basic standardized interface for performing in-code logical assertions with optional, customizable error reporting.
+
BookmarkHTMLUtils.jsm
+
Provides utility functions for importing and exporting bookmarks from the old-school "bookmarks.html" style bookmark files.
+
ctypes.jsm
+
Provides an interface that allows JavaScript code to call native libraries without requiring the development of an XPCOM component.
+
CustomizableUI.jsm
+
Allows you to interact with customizable buttons and items in Firefox's main window UI.
+
DeferredTask.jsm
+
Run a task after a delay.
+
Dict.jsm
+
Provides an API for key/value pair dictionaries.
+
DownloadLastDir.jsm
+
Supplies the path to the directory into which the last download occurred.
+
Downloads.jsm
+
Provides a single entry point to interact with the downloading capabilities of the platform.
+
FileUtils.jsm
+
Provides helpers for dealing with files.
+
Geometry.jsm
+
Provides routines for performing basic geometric operations on points and rectangles.
+
HTTP.jsm
+
A wrapper for XMLHttpRequest that provides convenient and simplified API for dealing with HTTP requests.
+
JNI.jsm
+
Abstracts the js-ctypes to provide an interface that allows JavaScript code to call code running in native JVMs.
+
ISO8601DateUtils.jsm
+
Provides routines to convert between JavaScript Date objects and ISO 8601 date strings.
+
Log.jsm (formerly log4moz)
+
Provides a log4j style API for logging, log messages to various endpoints, such as the Browser Console or a file on disk. 
+
+
+ +
+
+
NetUtil.jsm
+
Provides helpful networking utility functions, including the ability to easily copy data from an input stream to an output stream asynchronously.
+
openLocationLastURL.jsm
+
Provides access to the last URL opened using the "Open Location" option in the File menu.
+
OSFile.jsm
+
Allows routines to access files. To which can be read, write, rename, create directories,etc.
+
PerfMeasurement.jsm
+
Provides access to low-level hardware and OS performance measurement tools.
+
PluralForm.jsm
+
Supplies an easy way to get the correct plural forms for the current locale, as well as ways to localize to a specific plural rule.
+
PopupNotifications.jsm
+
Gives an easy way to present non-modal notifications to users.
+
Promise.jsm
+
Implements the Promises/A+ proposal as known in April 2013.
+
PromiseWorker.jsm
+
A version of {{domxref("ChromeWorker")}} which uses Promises to return the worker's result instead of using an event to do so.
+
Services.jsm
+
Provides getters for conveniently obtaining access to commonly-used services.
+
source-editor.jsm
+
The Source Editor is used by developer tools such as, the Style Editor; this interface implements the editor and lets you interact with it.
+
Sqlite.jsm
+
A Promise-based API to mozIStorage/SQLite.
+
Task.jsm
+
Implements a subset of Task.js to make sequential, asynchronous operations simple, using the power of JavaScript's yield operator.
+
Timer.jsm
+
A pure JS implementation of window.setTimeout.
+
Webapps.jsm
+
Provides an interface to manage Open Web Apps.
+
WebRequest.jsm
+
Provides an API to add event listeners for the various stages of making an HTTP request. The event listener receives detailed information about the request, and can modify or cancel the request.
+
XPCOMUtils.jsm
+
Contains utilities for JavaScript components loaded by the JS component loader.
+
+
+
+ + + + diff --git a/files/he/mozilla/projects/index.html b/files/he/mozilla/projects/index.html new file mode 100644 index 0000000000..d7e62c6882 --- /dev/null +++ b/files/he/mozilla/projects/index.html @@ -0,0 +1,15 @@ +--- +title: Projects +slug: Mozilla/Projects +tags: + - Landing + - Mozilla + - NeedsContent + - NeedsTranslation + - Projects + - TopicStub +translation_of: Mozilla/Projects +--- +

Here you'll find links to documentation about various Mozilla projects; these are often parts of Firefox or other products, but may also be used in other projects as well.

+ +

{{ LandingPageListSubpages() }}

diff --git a/files/he/mozilla/projects/rhino/index.html b/files/he/mozilla/projects/rhino/index.html new file mode 100644 index 0000000000..97f954eb40 --- /dev/null +++ b/files/he/mozilla/projects/rhino/index.html @@ -0,0 +1,26 @@ +--- +title: Rhino +slug: Mozilla/Projects/Rhino +tags: + - Rhino + - ג'אווה סקריפט + - מוזילה +translation_of: Mozilla/Projects/Rhino +--- +

Image:rhino.jpg

+ +

Rhino (קרנף) הוא מימוש קוד-פתוח של ג'אווה סקריפט שנכתב כולו בג'אווה. בדרך כלל הוא מוטמע ביישומי ג'אווה כדי לספק תסריטים למשתמשי קצה. הוא מוטמע ב-J2SE 6 כמנוע התסריטים ברירת המחדל של ג'אווה.

+ +

הורדות Rhino

+ +

כיצד להשיג את המקור והבינאריים

+ +

תיעוד Rhino

+ +

מידע אודות Rhino לכותבי תסריטים ומטמיעים.

+ +

עזרה ל-Rhino

+ +

כמה משאבים אם נתקעת.

+ +

{{ languages( { "ja": "ja/Rhino" } ) }}

diff --git a/files/he/mozilla/projects/thunderbird/thunderbird_localization/index.html b/files/he/mozilla/projects/thunderbird/thunderbird_localization/index.html new file mode 100644 index 0000000000..99310e33a9 --- /dev/null +++ b/files/he/mozilla/projects/thunderbird/thunderbird_localization/index.html @@ -0,0 +1,98 @@ +--- +title: Thunderbird Localization +slug: Mozilla/Projects/Thunderbird/Thunderbird_Localization +tags: + - גיור + - לוקליזציה +translation_of: Mozilla/Projects/Thunderbird/Thunderbird_Localization +--- +

This page is aimed at current and future localizers of Thunderbird, Mozilla Messaging's e-mail and usenet client. It covers many aspects a localizer of Thunderbird should be aware of like necessary tools, how to get information about localization-relevant events and various other items of interest.

+ +

Creating a Thunderbird localization

+ +

Creating a new localization (Mercurial) - This article describes how you can create a new localization for Thunderbird.

+ +

About repostories and branches

+ +

There are 3 active repositories for Thunderbird development. Thunderbird development work is merged from one branch to the next every six weeks.

+ + + +

Most locales will being working on comm-aurora. This repository/branch is stable with respect to strings for each six week period. Completing work here means it is ready for the first beta, and you won't need to work on beta branch. Your work will also automatically be carried forward.

+ +

Localization Requirements

+ +

There are not significant restrictions on what locales can change. However, we need to work together on providing search engines for Thunderbird users to use to get the right balance of search engines and the correct options set. For further information see this page.

+ +

Localization Dashboard

+ +

The localization dashboard for Thunderbird gives localizers a precise overview of the current status of their localization. Detailed information is available on the l10n dashboard page.

+ +

A localization will added to the l10n dashboard on request when it has reached a high-level of completion (> 80%) as shown by the compare-locales output. To request the addition of your locale to the dashboard, file a bug in the Thunderbird product/Build Config component.

+ +

Getting l10n-relevant information

+ +

Newsgroups & Mailinglists

+ +

Localizers of Thunderbird should read the localization newsgroups (mozilla.dev.l10n.announce mozilla.dev.l10n) to stay informed of Thunderbird-specific and general l10n-related items of interest to them. They are further encouraged to read the Thunderbird development newsgroup (mozilla.dev.apps.thunderbird) to stay informed of recent Thunderbird-related developments.

+ +

These newsgroups can also be accessed via the dev-l10n-announce@lists.mozilla.org, dev-l10n@lists.mozilla.org (localization mailinglist) or dev-apps-thunderbird@lists.mozilla.org (Thunderbird development mailinglist) mailinglists, which mirror the newsgroups mentioned above. You can subscribe to or unsubscribe from these mailinglists via the web interface at lists.mozilla.org.

+ +

Bugzilla

+ +

Localizers should watch the thunderbird@localization.bugs mail address (or its alias :tb-l10n) to stay current on bugs that might affect Thunderbird localizers. This can be done by adding this mail address to the "User Watching" section of your Email preferences in bugzilla.

+ + + + + +

Locale Tiers

+ +

Locale tiers reflect locales that we need to have in a good state for release. There are 10 locales in tier 1, which are the most important for Thunderbird, because of their number of Thunderbird users or potential for growth.

+ +

These locales are being treated as first-class citizens, as important as en-US, which is to say that any Tier 1 locale that does not meet the requirements may block a final release of Thunderbird.

+ +

Tier 1

+ +

The following are P1 (priority 1) locales in order of priority:

+ +
* de             -  German
+* fr             -  French
+* ja, ja-JP-mac  -  Japanese
+* en-GB          -  British English
+* es-ES          -  Spanish (European continent)
+* it             -  Italian
+* pl             -  Polish
+* ru             -  Russian
+* nl             -  Dutch
+* pt-BR          -  Brazilian Portuguese
+
+ +

Tier 2

+ +

All other supported locales are in the tier 2 category.

diff --git a/files/he/mozilla_mathml_project/index.html b/files/he/mozilla_mathml_project/index.html new file mode 100644 index 0000000000..2b45c419b6 --- /dev/null +++ b/files/he/mozilla_mathml_project/index.html @@ -0,0 +1,76 @@ +--- +title: Mozilla MathML Project +slug: Mozilla_MathML_Project +tags: + - MathML + - MathML Project + - NeedsTranslation + - TopicStub +translation_of: Mozilla/MathML_Project +--- +

Updates

+

mathboard.png

+ +

November 16, 2012

+

MathML and Thunderbird

+

November 14, 2012

+

Writing mathematics in emails

+

October 12, 2012

+

MathML has been enabled in Chrome Canary!

+

September 25, 2012

+

Story of a MathML summer project by Quentin Headen: Summer of Mozilla.

+

September 1, 2012

+

Mozilla MathML Project: Roadmap

+

Thank you to all the contributors who have worked on the MathML project this summer!

+

May 3, 2012

+

New MathJax option available in Wikipedia. If you have a Wikipedia account, mathematical formulas can now be rendered with MathML!

+

Community

+ + + +

Sample MathML Documents

+ +

Create MathML Documents

+ +
+

Original Document Information

+ +
+

 

+
+  
diff --git a/files/he/mozilla_mathml_project/start/index.html b/files/he/mozilla_mathml_project/start/index.html new file mode 100644 index 0000000000..2a2b864163 --- /dev/null +++ b/files/he/mozilla_mathml_project/start/index.html @@ -0,0 +1,77 @@ +--- +title: MathML בפעולה +slug: Mozilla_MathML_Project/Start +translation_of: Mozilla/MathML_Project/Start +--- +

MathML בפעולה

+

האם אתה רואה משוואות מגניבות בדף הזה? לא? חבל. הנה צילום מסך של מה שאתה מפסיד. הורד Mozilla עם MathML כדי לתקן מצב עצוב זה.

+

כבר יש לך תמיכה ב־MathML אך מה שאתה רואה בצילום המסך אינו מה שאתה מקבל? במקרה זה, כניראה חסרים לך גופני MathML חשובים.

+

עתה, לאחר שהצטיידת כהלכה, אתה צריך להיות מסוגל לראות את המשוואה הזאת עם תגים שונים: x ^ + xy ^ + xyz ^ . לצידה משוואה זעירה זו, det | a c b d | = a d - b c , שניתן גם לעצב בתצוגת תיבה נפרדת det | a b c d | = a d - b c .

+

סימול מתמטי הוא בררן. מטרת MathML ב־Mozilla היא להתאים לתקן MathML כך שמה שאתה רואה הוא מה שאתה מסמן, או במילים אחרות, מה שאתה רואה הוא מה שעשית, או בקיצור "WYSIWYM". ההבדל בין שני אלה הוא בסימון (markup)! ( ... ( ( a 0 + a 1 ) n 1 + a 2 ) n 2 + ... + a p ) n p ( ... ( ( a 0 + a 1 ) n 1 + a 2 ) n 2 + ... + a p ) n p

+

שורשי משוואה מודגשת זו y 3 + p y + q = 0 מודגשים גם הם y = - q 2 + q 2 4 + p 3 27 2 3 + - q 2 - q 2 4 + p 3 27 2 3 .

+

באשר לשורשי המשוואה a x 2 + b x + c = 0 , לחץ עם העכבר בכל מקום באיזור הצהוב כדי להגדיל/להקטין:

+
+

Zoomable Math

+

HTML Content

+
    <p>
+      <math display="block">
+        <mstyle id="zoomableMath" mathbackground="yellow">
+          <mrow>
+            <mi>x</mi>
+            <mo>=</mo>
+            <mfrac>
+              <mrow>
+                <mrow>
+                  <mo>-</mo>
+                  <mi>b</mi>
+                </mrow>
+                <mo>&#xB1;</mo>
+                <msqrt>
+                  <mrow>
+                    <msup>
+                      <mi>b</mi>
+                      <mn>2</mn>
+                    </msup>
+                    <mo>-</mo>
+                    <mrow>
+                      <mn>4</mn>
+                      <mi>a</mi>
+                      <mi>c</mi>
+                    </mrow>
+                  </mrow>
+                </msqrt>
+              </mrow>
+              <mrow>
+                <mn>2</mn>
+                <mi>a</mi>
+              </mrow>
+            </mfrac>
+          </mrow>
+        </mstyle>
+      </math>
+    </p>
+
+
+

JavaScript Content

+
      function zoomToggle()
+      {
+      if (this.hasAttribute("mathsize")) {
+      this.removeAttribute("mathsize");
+      } else {
+      this.setAttribute("mathsize", "200%");
+      }
+      }
+
+      function load()
+      {
+      document.getElementById("zoomableMath").
+      addEventListener("click", zoomToggle, false);
+      }
+
+      window.addEventListener("load", load, false);
+
+

{{ EmbedLiveSample('Zoomable_Math') }}

+

שים לב לסימון מעניין כמו זה { u t + f ( u ) x = 0 u ( 0 , x ) = { u - if  x < 0 u + if  x > 0 או לסימונים מורכבים אחרים כמו אלה Ell ^ Y ( Z ; z , τ ) := Y ( l ( y l 2 π i ) θ ( y l 2 π i - z ) θ ( 0 ) θ ( - z ) θ ( y l 2 π i ) ) × ( k θ ( e k 2 π i - ( α k + 1 ) z ) θ ( - z ) θ ( e k 2 π i - z ) θ ( - ( α k + 1 ) z ) ) π ( n ) = m = 2 n ( k = 1 m - 1 ( m / k ) / m / k ) - 1 ϕ W s k ( Ω g ) ( | α | k α ϕ ξ α L s ( Ω g ) s ) 1 / s

+

לדוגמאות נוספות, פנה לקישורים בדף פרוייקט MathML, ואם אתה בונה קובץ הפעלה של Mozilla משלך, ראה את המדריך mozilla/layout/mathml/tests.

+

עכשיו, מה הלאה? כאשר אתה מנסה את MathML ב־Mozilla, מה אתה עושה עם הדברים המועטים שנראה לך שאינם פועלים על פי מפרט MathML? ומה עם הדברים האלה שפשוט נראים מציקים, ושהיית רוצה שהיו נעשים קצת יותר טוב? ומה עם הדברים שפעלו בעבר ושאינם פועלים עוד (מכונים גם "רגרסיות")? בכל מקרה, עבור אל Bugzilla כדי לדווח על התקלות. ל־Bugzilla יש זיכרון גדול עבור הדברים האלו, וחוץ מזה, איך הבעיות שלך יתוקנו אם הן לא ידווחו?!

+

להיות מעורב הוא חלק מן התרומה שלך להעשרת גקו במפענח MatML אלגנטי ותואם לתקנים. המשוב שלך יכול להתבטא בהצגת תוכן MathML ברשת, דיווח על באגים ב־Bugzilla, ואם אתה יכול לעזור בקידוד, בבחינה/שיפור הקוד הקיים, ו/או לקיחת טיפול בפריט ברשימת הדברים לעשות.

diff --git a/files/he/sandbox/index.html b/files/he/sandbox/index.html new file mode 100644 index 0000000000..c245281460 --- /dev/null +++ b/files/he/sandbox/index.html @@ -0,0 +1,88 @@ +--- +title: ארגז חול +slug: Sandbox +tags: + - ארגז חול + - חול חדש + - חול חום + - תרגול +translation_of: Sandbox +--- +

{{EmbedLiveSample('Sample')}}

+ +

כיצד לערוך את ארגז החול לצורך פרסום

+ +

צריך להיות תוסף לעריכת וידאו.

+ +

עוד בקטע מאמר זה (אולי)

+ +

קינון?

+ +

המממ, אולי זה עוד?אני לא יודע.

+ +

כותרת H4

+ +
כותרת h5 היא סימן שחפרת יותר מדי פנימה!
+ +

דוגמת קוד

+ +
#include <iostream>
+
+int main()
+
+{
+
+print("This is a sample code!");
+
+return 3;
+
+}
+ +

My Alert

+ +

HTML

+ +
<p id='test_code'>
+  Test Sample Code
+</p>
+ +

CSS

+ +
#test_code {
+  background-color: purple;
+}
+ +

JavaScript

+ +
console.log("Hi there !!");
+ +

תוצאה

+ +

{{EmbedLiveSample('My_Alert')}}

+ +

Hello World

+ +

HTML

+ +
<input type="date">
+
+ +

תוצאה

+ +

{{EmbedLiveSample('Hello_World')}}

+ +

סיכום

+ +

מסמך זה מיועד לביסוס מידע.

+ +

יסודות ה- WebGL

+ +

מתודת shaderSource של WebglRenderingContext מגניבה לגמרי!

+ +

ניווט משנה

+ + diff --git a/files/he/web/api/console/index.html b/files/he/web/api/console/index.html new file mode 100644 index 0000000000..61521af0f3 --- /dev/null +++ b/files/he/web/api/console/index.html @@ -0,0 +1,294 @@ +--- +title: Console +slug: Web/API/Console +tags: + - API + - Debugging + - Interface + - NeedsTranslation + - Reference + - TopicStub + - console + - web console +translation_of: Web/API/Console +--- +
{{APIRef("Console API")}}
+ +

The Console object provides access to the browser's debugging console (e.g. the Web Console in Firefox). The specifics of how it works varies from browser to browser, but there is a de facto set of features that are typically provided.

+ +

The Console object can be accessed from any global object. {{domxref("Window")}} on browsing scopes and {{domxref("WorkerGlobalScope")}} as specific variants in workers via the property console. It's exposed as {{domxref("Window.console")}}, and can be referenced as simply console. For example:

+ +
console.log("Failed to open the specified link")
+ +

This page documents the {{anch("Methods")}} available on the Console object and gives a few {{anch("Usage")}} examples.

+ +

{{AvailableInWorkers}}

+ +

Methods

+ +
+
{{domxref("Console.assert()")}}
+
Log a message and stack trace to console if the first argument is false.
+
{{domxref("Console.clear()")}}
+
Clear the console.
+
{{domxref("Console.count()")}}
+
Log the number of times this line has been called with the given label.
+
{{domxref("Console.countReset()")}}
+
Resets the value of the counter with the given label.
+
{{domxref("Console.debug()")}}
+
Outputs a message to the console with the log level "debug". +
Note: Starting with Chromium 58 this method only appears in Chromium browser consoles when level "Verbose" is selected.
+
+
{{domxref("Console.dir()")}}
+
Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.
+
{{domxref("Console.dirxml()")}}
+
+

Displays an XML/HTML Element representation of the specified object if possible or the JavaScript Object view if it is not possible.

+
+
{{domxref("Console.error()")}}
+
Outputs an error message. You may use string substitution and additional arguments with this method.
+
{{domxref("Console.exception()")}} {{Non-standard_inline}} {{deprecated_inline}}
+
An alias for error().
+
{{domxref("Console.group()")}}
+
Creates a new inline group, indenting all following output by another level. To move back out a level, call groupEnd().
+
{{domxref("Console.groupCollapsed()")}}
+
Creates a new inline group, indenting all following output by another level. However, unlike group() this starts with the inline group collapsed requiring the use of a disclosure button to expand it. To move back out a level, call groupEnd().
+
{{domxref("Console.groupEnd()")}}
+
Exits the current inline group.
+
{{domxref("Console.info()")}}
+
Informative logging of information. You may use string substitution and additional arguments with this method.
+
{{domxref("Console.log()")}}
+
For general output of logging information. You may use string substitution and additional arguments with this method.
+
{{domxref("Console.profile()")}} {{Non-standard_inline}}
+
Starts the browser's built-in profiler (for example, the Firefox performance tool). You can specify an optional name for the profile.
+
{{domxref("Console.profileEnd()")}} {{Non-standard_inline}}
+
Stops the profiler. You can see the resulting profile in the browser's performance tool (for example, the Firefox performance tool).
+
{{domxref("Console.table()")}}
+
Displays tabular data as a table.
+
{{domxref("Console.time()")}}
+
Starts a timer with a name specified as an input parameter. Up to 10,000 simultaneous timers can run on a given page.
+
{{domxref("Console.timeEnd()")}}
+
Stops the specified timer and logs the elapsed time in seconds since it started.
+
{{domxref("Console.timeLog()")}}
+
Logs the value of the specified timer to the console.
+
{{domxref("Console.timeStamp()")}} {{Non-standard_inline}}
+
Adds a marker to the browser's Timeline or Waterfall tool.
+
{{domxref("Console.trace()")}}
+
Outputs a stack trace.
+
{{domxref("Console.warn()")}}
+
Outputs a warning message. You may use string substitution and additional arguments with this method.
+
+ +

Usage

+ +

Outputting text to the console

+ +

The most frequently-used feature of the console is logging of text and other data. There are four categories of output you can generate, using the {{domxref("console.log()")}}, {{domxref("console.info()")}}, {{domxref("console.warn()")}}, and {{domxref("console.error()")}} methods respectively. Each of these results in output styled differently in the log, and you can use the filtering controls provided by your browser to only view the kinds of output that interest you.

+ +

There are two ways to use each of the output methods; you can simply pass in a list of objects whose string representations get concatenated into one string, then output to the console, or you can pass in a string containing zero or more substitution strings followed by a list of objects to replace them.

+ +

Outputting a single object

+ +

The simplest way to use the logging methods is to output a single object:

+ +
var someObject = { str: "Some text", id: 5 };
+console.log(someObject);
+
+ +

The output looks something like this:

+ +
[09:27:13.475] ({str:"Some text", id:5})
+ +

Outputting multiple objects

+ +

You can also output multiple objects by simply listing them when calling the logging method, like this:

+ +
var car = "Dodge Charger";
+var someObject = { str: "Some text", id: 5 };
+console.info("My first car was a", car, ". The object is:", someObject);
+ +

This output will look like this:

+ +
[09:28:22.711] My first car was a Dodge Charger . The object is: ({str:"Some text", id:5})
+
+ +

Using string substitutions

+ +

Gecko 9.0 {{geckoRelease("9.0")}} introduced support for string substitutions. When passing a string to one of the console object's methods that accepts a string, you may use these substitution strings:

+ + + + + + + + + + + + + + + + + + + + + + + + +
Substitution stringDescription
%o or %OOutputs a JavaScript object. Clicking the object name opens more information about it in the inspector.
%d or %iOutputs an integer. Number formatting is supported, for example  console.log("Foo %.2d", 1.1) will output the number as two significant figures with a leading 0: Foo 01
%sOutputs a string.
%fOutputs a floating-point value. Formatting is supported, for example  console.log("Foo %.2f", 1.1) will output the number to 2 decimal places: Foo 1.10
+ +
+

Note: Precision formatting doesn't work in Chrome

+
+ +

Each of these pulls the next argument after the format string off the parameter list. For example:

+ +
for (var i=0; i<5; i++) {
+  console.log("Hello, %s. You've called me %d times.", "Bob", i+1);
+}
+
+ +

The output looks like this:

+ +
[13:14:13.481] Hello, Bob. You've called me 1 times.
+[13:14:13.483] Hello, Bob. You've called me 2 times.
+[13:14:13.485] Hello, Bob. You've called me 3 times.
+[13:14:13.487] Hello, Bob. You've called me 4 times.
+[13:14:13.488] Hello, Bob. You've called me 5 times.
+
+ +

Styling console output

+ +

You can use the %c directive to apply a CSS style to console output:

+ +
console.log("This is %cMy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px");
+ +
The text before the directive will not be affected, but the text after the directive will be styled using the CSS declarations in the parameter.
+ +
 
+ +
+ +
 
+ +
+

Note: Quite a few CSS properties are supported by this styling; you should experiment and see which ones prove useful.

+
+ +
 
+ +
{{h3_gecko_minversion("Using groups in the console", "9.0")}}
+ +

You can use nested groups to help organize your output by visually combining related material. To create a new nested block, call console.group(). The console.groupCollapsed() method is similar but creates the new block collapsed, requiring the use of a disclosure button to open it for reading.

+ +
Note: Collapsed groups are not supported yet in Gecko; the groupCollapsed() method is the same as group() at this time.
+ +

To exit the current group, simply call console.groupEnd(). For example, given this code:

+ +
console.log("This is the outer level");
+console.group();
+console.log("Level 2");
+console.group();
+console.log("Level 3");
+console.warn("More of level 3");
+console.groupEnd();
+console.log("Back to level 2");
+console.groupEnd();
+console.debug("Back to the outer level");
+
+ +

The output looks like this:

+ +

nesting.png

+ +
{{h3_gecko_minversion("Timers", "10.0")}}
+ +

In order to calculate the duration of a specific operation, Gecko 10 introduced the support of timers in the console object. To start a timer, call the console.time() method, giving it a name as the only parameter. To stop the timer, and to get the elapsed time in milliseconds, just call the console.timeEnd() method, again passing the timer's name as the parameter. Up to 10,000 timers can run simultaneously on a given page.

+ +

For example, given this code:

+ +
console.time("answer time");
+alert("Click to continue");
+console.timeLog("answer time");
+alert("Do a bunch of other stuff...");
+console.timeEnd("answer time");
+
+ +

Will log the time needed by the user to dismiss the alert box, log the time to the console, wait for the user to dismiss the second alert, and then log the ending time to the console:

+ +

timerresult.png

+ +

Notice that the timer's name is displayed both when the timer is started and when it's stopped.

+ +
Note: It's important to note that if you're using this to log the timing for network traffic, the timer will report the total time for the transaction, while the time listed in the network panel is just the amount of time required for the header. If you have response body logging enabled, the time listed for the response header and body combined should match what you see in the console output.
+ +

Stack traces

+ +

The console object also supports outputting a stack trace; this will show you the call path taken to reach the point at which you call {{domxref("console.trace()")}}. Given code like this:

+ +
function foo() {
+  function bar() {
+    console.trace();
+  }
+  bar();
+}
+
+foo();
+
+ +

The output in the console looks something like this:

+ +

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Console API')}}{{Spec2('Console API')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.Console")}}

+ +

Notes

+ + + +

See also

+ + + +

Other implementations

+ + diff --git a/files/he/web/api/console/log/index.html b/files/he/web/api/console/log/index.html new file mode 100644 index 0000000000..8ea8ab6218 --- /dev/null +++ b/files/he/web/api/console/log/index.html @@ -0,0 +1,39 @@ +--- +title: Console.log() +slug: Web/API/Console/log +translation_of: Web/API/Console/log +--- +
{{APIRef("Console API")}}
+ +

()Console.log - מציגה את פלט ההודעה באזור המסוף של דפדפן האינטרנט.

+ +

תחביר

+ +
console.log(obj1 [, obj2, ..., objN]);
+console.log(msg [, subst1, ..., substN]);
+
+ +

מפרט

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#log", "console.log()")}}{{Spec2("Console API")}}Initial definition
+ +

תאימות דפדפן

+ + + +

{{Compat("api.Console.log")}}

diff --git a/files/he/web/api/document/index.html b/files/he/web/api/document/index.html new file mode 100644 index 0000000000..d380692a64 --- /dev/null +++ b/files/he/web/api/document/index.html @@ -0,0 +1,488 @@ +--- +title: Document +slug: Web/API/Document +tags: + - API + - DOM + - Document + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/Document +--- +

The Document interface represents any web page loaded in the browser and serves as an entry point into the web page's content, which is the DOM tree. The DOM tree includes elements such as {{HTMLElement("body")}} and {{HTMLElement("table")}}, among many others. It provides functionality globally to the document, like how to obtain the page's URL and create new elements in the document.

+ +

{{inheritanceDiagram}}

+ +

The Document interface describes the common properties and methods for any kind of document. Depending on the document's type (e.g. HTML, XML, SVG, …), a larger API is available: HTML documents, served with the "text/html" content type, also implement the {{domxref("HTMLDocument")}} interface, whereas XML and SVG documents implement the {{domxref("XMLDocument")}} interface.

+ +

Constructor

+ +
+
{{domxref("Document.Document","Document()")}}{{non-standard_inline}}
+
Creates a new Document object.
+
+ +

Properties

+ +

This interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.

+ +
+
{{domxref("Document.anchors")}} {{readonlyinline}}
+
Returns a list of all of the anchors in the document.
+
{{domxref("Document.body")}}
+
Returns the {{HTMLElement("body")}} or {{htmlelement("frameset")}} node of the current document.
+
{{domxref("Document.characterSet")}} {{readonlyinline}}
+
Returns the character set being used by the document.
+
{{domxref("Document.compatMode")}} {{readonlyinline}} {{experimental_inline}}
+
Indicates whether the document is rendered in quirks or strict mode.
+
{{domxref("Document.contentType")}} {{readonlyinline}} {{experimental_inline}}
+
Returns the Content-Type from the MIME Header of the current document.
+
{{domxref("Document.doctype")}} {{readonlyinline}}
+
Returns the Document Type Definition (DTD) of the current document.
+
{{domxref("Document.documentElement")}} {{readonlyinline}}
+
Returns the {{domxref("Element")}} that is a direct child of the document. For HTML documents, this is normally the {{domxref("HTMLElement")}} element.
+
{{domxref("Document.documentURI")}} {{readonlyinline}}
+
Returns the document location as a string.
+
{{domxref("Document.embeds")}} {{readonlyinline}}
+
Returns a list of the embedded {{HTMLElement('embed')}} elements within the current document.
+
{{domxref("Document.fonts")}}
+
Returns the {{domxref("FontFaceSet")}} interface of the current document.
+
{{domxref("Document.forms")}} {{readonlyinline}}
+
Returns a list of the {{HTMLElement("form")}} elements within the current document.
+
{{domxref("Document.head")}} {{readonlyinline}}
+
Returns the {{HTMLElement("head")}} element of the current document.
+
{{domxref("Document.hidden")}} {{readonlyinline}}
+
+
{{domxref("Document.images")}} {{readonlyinline}}
+
Returns a list of the images in the current document.
+
{{domxref("Document.implementation")}} {{readonlyinline}}
+
Returns the DOM implementation associated with the current document.
+
{{domxref("Document.lastStyleSheetSet")}} {{readonlyinline}}
+
Returns the name of the style sheet set that was last enabled. Has the value null until the style sheet is changed by setting the value of {{domxref("document.selectedStyleSheetSet","selectedStyleSheetSet")}}.
+
{{domxref("Document.links")}} {{readonlyinline}}
+
Returns a list of all the hyperlinks in the document.
+
{{domxref("Document.mozSyntheticDocument")}} {{non-standard_inline}} {{gecko_minversion_inline("8.0")}}
+
Returns a {{jsxref("Boolean")}} that is true only if this document is synthetic, such as a standalone image, video, audio file, or the like.
+
{{domxref("Document.mozFullScreenElement")}} {{readonlyinline}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
+
The element that's currently in full screen mode for this document.
+
{{domxref("Document.mozFullScreenEnabled")}} {{readonlyinline}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
+
true if calling {{domxref("Element.mozRequestFullscreen()")}} would succeed in the current document.
+
{{domxref("Document.plugins")}} {{readonlyinline}}
+
Returns a list of the available plugins.
+
{{domxref("Document.policy")}} {{readonlyinline}}{{experimental_inline}}
+
Returns the {{domxref("Policy")}} interface which provides a simple API for introspecting the feature policies applied to a specific document.
+
{{domxref("Document.preferredStyleSheetSet")}} {{readonlyinline}}
+
Returns the preferred style sheet set as specified by the page author.
+
{{domxref("Document.scripts")}} {{readonlyinline}}
+
Returns all the {{HTMLElement("script")}} elements on the document.
+
{{domxref("Document.scrollingElement")}} {{readonlyinline}}
+
Returns a reference to the {{domxref("Element")}} that scrolls the document.
+
{{domxref("Document.selectedStyleSheetSet")}}
+
Returns which style sheet set is currently in use.
+
{{domxref("Document.styleSheetSets")}} {{readonlyinline}}
+
Returns a list of the style sheet sets available on the document.
+
{{domxref("Document.timeline")}} {{readonlyinline}}
+
+
{{domxref("Document.undoManager")}} {{readonlyinline}} {{experimental_inline}}
+
+
{{domxref("Document.visibilityState")}} {{readonlyinline}}
+
Returns a string denoting the visibility state of the document. Possible values are visiblehiddenprerender, and unloaded.
+
+ +

The Document interface is extended with the {{domxref("ParentNode")}} interface:

+ +

{{page("/en-US/docs/Web/API/ParentNode","Properties")}}

+ +

Extensions for HTMLDocument

+ +

The Document interface for HTML documents inherits from the {{domxref("HTMLDocument")}} interface or, since HTML5,  is extended for such documents.

+ +
+
{{domxref("Document.cookie")}}
+
Returns a semicolon-separated list of the cookies for that document or sets a single cookie.
+
{{domxref("Document.defaultView")}} {{readonlyinline}}
+
Returns a reference to the window object.
+
{{domxref("Document.designMode")}}
+
Gets/sets the ability to edit the whole document.
+
{{domxref("Document.dir")}} {{readonlyinline}}
+
Gets/sets directionality (rtl/ltr) of the document.
+
{{domxref("Document.domain")}}
+
Gets/sets the domain of the current document.
+
{{domxref("Document.lastModified")}} {{readonlyinline}}
+
Returns the date on which the document was last modified.
+
{{domxref("Document.location")}} {{readonlyinline}}
+
Returns the URI of the current document.
+
{{domxref("Document.readyState")}} {{readonlyinline}} {{gecko_minversion_inline("1.9.2")}}
+
Returns loading status of the document.
+
{{domxref("Document.referrer")}} {{readonlyinline}}
+
Returns the URI of the page that linked to this page.
+
{{domxref("Document.title")}}
+
Sets or gets the title of the current document.
+
{{domxref("Document.URL")}} {{readonlyInline}}
+
Returns the document location as a string.
+
+ +

Properties included from DocumentOrShadowRoot

+ +

The Document interface includes the following properties defined on the {{domxref("DocumentOrShadowRoot")}} mixin. Note that this is currently only implemented by Chrome; other browsers still implement them directly on the {{domxref("Document")}} interface.

+ +
+
{{domxref("DocumentOrShadowRoot.activeElement")}} {{readonlyInline}}
+
Returns the {{domxref('Element')}} within the shadow tree that has focus.
+
{{domxref("Document.fullscreenElement")}} {{readonlyinline}}
+
The element that's currently in full screen mode for this document.
+
{{domxref("DocumentOrShadowRoot.pointerLockElement")}} {{readonlyinline}} {{experimental_inline}}
+
Returns the element set as the target for mouse events while the pointer is locked. null if lock is pending, pointer is unlocked, or if the target is in another document.
+
{{domxref("DocumentOrShadowRoot.styleSheets")}} {{readonlyInline}}
+
Returns a {{domxref('StyleSheetList')}} of {{domxref('CSSStyleSheet')}} objects for stylesheets explicitly linked into, or embedded in a document.
+
+ +

Event handlers

+ +
+
{{domxref("Document.onafterscriptexecute")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("afterscriptexecute")}} event.
+
{{domxref("Document.onbeforescriptexecute")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("beforescriptexecute")}} event.
+
{{domxref("Document.oncopy")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("copy")}} event.
+
{{domxref("Document.oncut")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("cut")}} event.
+
{{domxref("Document.onfullscreenchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("fullscreenchange")}} event is raised.
+
{{domxref("Document.onfullscreenerror")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("fullscreenerror")}} event is raised.
+
{{domxref("Document.onpaste")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("paste")}} event.
+
{{domxref("Document.onpointerlockchange")}} {{experimental_inline}}
+
Represents the event handling code for the {{event("pointerlockchange")}} event.
+
{{domxref("Document.onpointerlockerror")}} {{experimental_inline}}
+
Represents the event handling code for the {{event("pointerlockerror")}} event.
+
{{domxref("Document.onreadystatechange")}} {{gecko_minversion_inline("1.9.2")}}
+
Represents the event handling code for the {{event("readystatechange")}} event.
+
{{domxref("Document.onselectionchange")}} {{experimental_inline}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.
+
{{domxref("Document.onvisibilitychange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("visibilitychange")}} event is raised.
+
{{domxref("Document.onwheel")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("wheel")}} event.
+
+ +

The Document interface is extended with the {{domxref("GlobalEventHandlers")}} interface:

+ +

{{Page("/en-US/docs/Web/API/GlobalEventHandlers", "Properties")}}

+ +

Deprecated properties

+ +
+
{{domxref("Document.alinkColor")}} {{Deprecated_inline}}
+
Returns or sets the color of active links in the document body.
+
{{domxref("Document.all")}} {{Deprecated_inline}} {{non-standard_inline}}
+
Provides access to all elements in the document. This is a legacy, non-standard property and should not be used.
+
{{domxref("Document.applets")}} {{Deprecated_inline}} {{readonlyinline}}
+
Returns an ordered list of the applets within a document.
+
{{domxref("Document.async")}} {{Deprecated_inline}}
+
Used with {{domxref("Document.load")}} to indicate an asynchronous request.
+
{{domxref("Document.bgColor")}} {{Deprecated_inline}}
+
Gets/sets the background color of the current document.
+
{{domxref("Document.charset")}} {{readonlyinline}} {{Deprecated_inline}}
+
Alias of {{domxref("Document.characterSet")}}. Use this property instead.
+
{{domxref("Document.domConfig")}} {{Deprecated_inline}}
+
Should return a {{domxref("DOMConfiguration")}} object.
+
{{domxref("document.fgColor")}} {{Deprecated_inline}}
+
Gets/sets the foreground color, or text color, of the current document.
+
{{domxref("Document.fullscreen")}} {{obsolete_inline}}
+
true when the document is in {{domxref("Using_full-screen_mode","full-screen mode")}}.
+
{{domxref("Document.height")}} {{non-standard_inline}} {{obsolete_inline}}
+
Gets/sets the height of the current document.
+
{{domxref("Document.inputEncoding")}} {{readonlyinline}} {{Deprecated_inline}}
+
Alias of {{domxref("Document.characterSet")}}. Use this property instead.
+
{{domxref("Document.linkColor")}} {{Deprecated_inline}}
+
Gets/sets the color of hyperlinks in the document.
+
{{domxref("Document.vlinkColor")}} {{Deprecated_inline}}
+
Gets/sets the color of visited hyperlinks.
+
{{domxref("Document.width")}} {{non-standard_inline}} {{obsolete_inline}}
+
Returns the width of the current document.
+
{{domxref("Document.xmlEncoding")}} {{Deprecated_inline}}
+
Returns the encoding as determined by the XML declaration.
+
{{domxref("Document.xmlStandalone")}} {{obsolete_inline("10.0")}}
+
Returns true if the XML declaration specifies the document to be standalone (e.g., An external part of the DTD affects the document's content), else false.
+
{{domxref("Document.xmlVersion")}} {{obsolete_inline("10.0")}}
+
Returns the version number as specified in the XML declaration or "1.0" if the declaration is absent.
+
+ +

Methods

+ +

This interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.

+ +
+
{{domxref("Document.adoptNode()")}}
+
Adopt node from an external document.
+
{{domxref("Document.captureEvents()")}} {{Deprecated_inline}}
+
See {{domxref("Window.captureEvents")}}.
+
{{domxref("Document.caretRangeFromPoint()")}}{{non-standard_inline}}
+
Gets a {{Domxref("Range")}} object for the document fragment under the specified coordinates.
+
{{domxref("Document.createAttribute()")}}
+
Creates a new {{domxref("Attr")}} object and returns it.
+
{{domxref("Document.createAttributeNS()")}}
+
Creates a new attribute node in a given namespace and returns it.
+
{{domxref("Document.createCDATASection()")}}
+
Creates a new CDATA node and returns it.
+
{{domxref("Document.createComment()")}}
+
Creates a new comment node and returns it.
+
{{domxref("Document.createDocumentFragment()")}}
+
Creates a new document fragment.
+
{{domxref("Document.createElement()")}}
+
Creates a new element with the given tag name.
+
{{domxref("Document.createElementNS()")}}
+
Creates a new element with the given tag name and namespace URI.
+
{{domxref("Document.createEntityReference()")}} {{obsolete_inline}}
+
Creates a new entity reference object and returns it.
+
{{domxref("Document.createEvent()")}}
+
Creates an event object.
+
{{domxref("Document.createNodeIterator()")}}
+
Creates a {{domxref("NodeIterator")}} object.
+
{{domxref("Document.createProcessingInstruction()")}}
+
Creates a new {{domxref("ProcessingInstruction")}} object.
+
{{domxref("Document.createRange()")}}
+
Creates a {{domxref("Range")}} object.
+
{{domxref("Document.createTextNode()")}}
+
Creates a text node.
+
{{domxref("Document.createTouch()")}} {{Deprecated_inline}}
+
Creates a {{domxref("Touch")}} object.
+
{{domxref("Document.createTouchList()")}}
+
Creates a {{domxref("TouchList")}} object.
+
{{domxref("Document.createTreeWalker()")}}
+
Creates a {{domxref("TreeWalker")}} object.
+
{{domxref("Document.enableStyleSheetsForSet()")}}
+
Enables the style sheets for the specified style sheet set.
+
{{domxref("Document.exitPointerLock()")}} {{experimental_inline}}
+
Release the pointer lock.
+
{{domxref("Document.getAnimations()")}} {{experimental_inline}}
+
Returns an array of all {{domxref("Animation")}} objects currently in effect, whose target elements are descendants of the document.
+
{{domxref("Document.getElementsByClassName()")}}
+
Returns a list of elements with the given class name.
+
{{domxref("Document.getElementsByTagName()")}}
+
Returns a list of elements with the given tag name.
+
{{domxref("Document.getElementsByTagNameNS()")}}
+
Returns a list of elements with the given tag name and namespace.
+
{{domxref("Document.importNode()")}}
+
Returns a clone of a node from an external document.
+
{{domxref("Document.normalizeDocument()")}} {{obsolete_inline}}
+
Replaces entities, normalizes text nodes, etc.
+
{{domxref("Document.releaseCapture()")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}
+
Releases the current mouse capture if it's on an element in this document.
+
{{domxref("Document.releaseEvents()")}} {{non-standard_inline}} {{Deprecated_inline}}
+
See {{domxref("Window.releaseEvents()")}}.
+
{{domxref("Document.routeEvent()")}} {{non-standard_inline}} {{obsolete_inline(24)}}
+
See {{domxref("Window.routeEvent()")}}.
+
{{domxref("Document.mozSetImageElement()")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}
+
Allows you to change the element being used as the background image for a specified element ID.
+
+ +

The Document interface is extended with the {{domxref("ParentNode")}} interface:

+ +
+
{{domxref("document.getElementById","document.getElementById(String id)")}}
+
Returns an object reference to the identified element.
+
{{domxref("document.querySelector","document.querySelector(String selector)")}} {{gecko_minversion_inline("1.9.1")}}
+
Returns the first Element node within the document, in document order, that matches the specified selectors.
+
{{domxref("document.querySelectorAll","document.querySelectorAll(String selector)")}} {{gecko_minversion_inline("1.9.1")}}
+
Returns a list of all the Element nodes within the document that match the specified selectors.
+
+ +

The Document interface is extended with the {{domxref("XPathEvaluator")}} interface:

+ +
+
{{domxref("document.createExpression","document.createExpression(String expression, XPathNSResolver resolver)")}}
+
Compiles an XPathExpression which can then be used for (repeated) evaluations.
+
{{domxref("document.createNSResolver","document.createNSResolver(Node resolver)")}}
+
Creates an {{domxref("XPathNSResolver")}} object.
+
{{domxref("document.evaluate","document.evaluate(String expression, Node contextNode, XPathNSResolver resolver, Number type, Object result)")}}
+
Evaluates an XPath expression.
+
+ +

Extension for HTML documents

+ +

The Document interface for HTML documents inherit from the {{domxref("HTMLDocument")}} interface or, since HTML5,  is extended for such documents:

+ +
+
{{domxref("document.clear()")}} {{non-standard_inline}} {{Deprecated_inline}}
+
In majority of modern browsers, including recent versions of Firefox and Internet Explorer, this method does nothing.
+
{{domxref("document.close()")}}
+
Closes a document stream for writing.
+
{{domxref("document.execCommand","document.execCommand(String command[, Boolean showUI[, String value]])")}}
+
On an editable document, executes a formating command.
+
{{domxref("document.getElementsByName","document.getElementsByName(String name)")}}
+
Returns a list of elements with the given name.
+
{{domxref("document.hasFocus()")}}
+
Returns true if the focus is currently located anywhere inside the specified document.
+
{{domxref("document.open()")}}
+
Opens a document stream for writing.
+
{{domxref("document.queryCommandEnabled","document.queryCommandEnabled(String command)")}}
+
Returns true if the formating command can be executed on the current range.
+
{{domxref("document.queryCommandIndeterm","document.queryCommandIndeterm(String command)")}}
+
Returns true if the formating command is in an indeterminate state on the current range.
+
{{domxref("document.queryCommandState","document.queryCommandState(String command)")}}
+
Returns true if the formating command has been executed on the current range.
+
{{domxref("document.queryCommandSupported","document.queryCommandSupported(String command)")}}
+
Returns true if the formating command is supported on the current range.
+
{{domxref("document.queryCommandValue","document.queryCommandValue(String command)")}}
+
Returns the current value of the current range for a formating command.
+
{{domxref("document.write","document.write(String text)")}}
+
Writes text in a document.
+
{{domxref("document.writeln","document.writeln(String text)")}}
+
Writes a line of text in a document.
+
+ +

Methods included from DocumentOrShadowRoot

+ +

The Document interface includes the following methods defined on the {{domxref("DocumentOrShadowRoot")}} mixin. Note that this is currently only implemented by Chrome; other browsers still implement them on the {{domxref("Document")}} interface.

+ +
+
{{domxref("DocumentOrShadowRoot.getSelection()")}}
+
Returns a {{domxref('Selection')}} object representing the range of text selected by the user, or the current position of the caret.
+
{{domxref("DocumentOrShadowRoot.elementFromPoint()")}}
+
Returns the topmost element at the specified coordinates.
+
{{domxref("DocumentOrShadowRoot.elementsFromPoint()")}}
+
Returns an array of all elements at the specified coordinates.
+
{{domxref("DocumentOrShadowRoot.caretPositionFromPoint()")}}
+
Returns a {{domxref('CaretPosition')}} object containing the DOM node containing the caret, and caret's character offset within that node.
+
+ +

Non-standard extensions {{non-standard_inline}}

+ +
{{non-standard_header}}
+ +

Firefox notes

+ +

Mozilla defines a set of non-standard properties made only for XUL content:

+ +
+
{{domxref("document.currentScript")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}
+
Returns the {{HTMLElement("script")}} element that is currently executing.
+
{{domxref("document.documentURIObject")}} {{gecko_minversion_inline("1.9")}}
+
(Mozilla add-ons only!) Returns the {{Interface("nsIURI")}} object representing the URI of the document. This property only has special meaning in privileged JavaScript code (with UniversalXPConnect privileges).
+
{{domxref("document.popupNode")}}
+
Returns the node upon which a popup was invoked.
+
{{domxref("document.tooltipNode")}}
+
Returns the node which is the target of the current tooltip.
+
+ +

Mozilla also define some non-standard methods:

+ +
+
{{domxref("document.execCommandShowHelp")}} {{obsolete_inline("14.0")}}
+
This method never did anything and always threw an exception, so it was removed in Gecko 14.0 {{geckoRelease("14.0")}}.
+
{{domxref("document.getBoxObjectFor")}} {{obsolete_inline}}
+
Use the {{domxref("Element.getBoundingClientRect()")}} method instead.
+
{{domxref("document.loadOverlay")}} {{Fx_minversion_inline("1.5")}}
+
Loads a XUL overlay dynamically. This only works in XUL documents.
+
{{domxref("document.queryCommandText")}} {{obsolete_inline("14.0")}}
+
This method never did anything but throw an exception, and was removed in Gecko 14.0 {{geckoRelease("14.0")}}.
+
+ +

Internet Explorer notes

+ +

Microsoft defines some non-standard properties:

+ +
+
{{domxref("document.fileSize")}}* {{non-standard_inline}} {{obsolete_inline}}
+
Returns size in bytes of the document. Starting with Internet Explorer 11, that property is no longer supported. See MSDN.
+
+ +

Internet Explorer does not support all methods from the Node interface in the Document interface:

+ +
+
{{domxref("document.contains")}}
+
As a work-around, document.body.contains() can be used.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#interface-document", "Document")}}{{Spec2("DOM WHATWG")}}Intend to supersede DOM 3
{{SpecName("HTML WHATWG", "dom.html#the-document-object", "Document")}}{{Spec2("HTML WHATWG")}}Turn the {{domxref("HTMLDocument")}} interface into a Document extension.
{{SpecName("HTML Editing", "#dom-document-getselection", "Document")}}{{Spec2("HTML Editing")}}Extend the Document interface
{{SpecName("CSSOM View", "#extensions-to-the-document-interface", "Document")}}{{Spec2("CSSOM View")}}Extend the Document interface
{{SpecName("CSSOM", "#extensions-to-the-document-interface", "Document")}}{{Spec2("CSSOM")}}Extend the Document interface
{{SpecName("Pointer Lock", "#extensions-to-the-document-interface", "Document")}}{{Spec2("Pointer Lock")}}Extend the Document interface
{{SpecName("Page Visibility API", "#extensions-to-the-document-interface", "Document")}}{{Spec2("Page Visibility API")}}Extend the Document interface with the visibilityState and hidden attributes and the onvisibilitychange event listener.
{{SpecName("Selection API", "#extensions-to-document-interface", "Document")}}{{Spec2("Selection API")}}Adds getSelection(), onselectstart and onselectionchange.
{{SpecName("DOM4", "#interface-document", "Document")}}{{Spec2("DOM4")}}Supersede DOM 3
{{SpecName("DOM3 Core", "#i-Document", "Document")}}{{Spec2("DOM3 Core")}}Supersede DOM 2
{{SpecName("DOM3 XPath", "xpath.html#XPathEvaluator", "XPathEvaluator")}}{{Spec2("DOM3 XPath")}}Define the {{domxref("XPathEvaluator")}} interface which extend document.
{{SpecName("DOM2 Core", "#i-Document", "Document")}}{{Spec2("DOM2 Core")}}Supersede DOM 1
{{SpecName("DOM1", "#i-Document", "Document")}}{{Spec2("DOM1")}}Initial definition for the interface
+ +

Browser compatibility

+ + + +

{{Compat("api.Document")}}

+ +
{{APIRef}}
diff --git a/files/he/web/api/document/write/index.html b/files/he/web/api/document/write/index.html new file mode 100644 index 0000000000..8c497d548c --- /dev/null +++ b/files/he/web/api/document/write/index.html @@ -0,0 +1,82 @@ +--- +title: 'Document.write():' +slug: Web/API/Document/write +translation_of: Web/API/Document/write +--- +
{{ ApiRef("DOM") }}
+ +

()Document.write - כותב מחרוזת טקסט אל גוף מסמך HTML.

+ +

תחביר

+ +
document.write(markup);
+
+ +

פרמטרים

+ +
+
markup
+
מחרוזת המכילה את הטקסט שיופיע במסמך.
+
+ +

דוגמה

+ +
<html>
+
+<head>
+  <title>write example</title>
+
+  <script>
+    function newContent() {
+      alert("load new content");
+      document.open();
+      document.write("<h1>Out with the old - in with the new!</h1>");
+      document.close();
+    }
+  </script>
+</head>
+
+<body onload="newContent();">
+  <p>Some original document content.</p>
+</body>
+
+</html>
+
+
+ +

מפרט

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "#dom-document-write", "document.write(...)")}}{{Spec2("HTML WHATWG")}} 
{{SpecName("DOM2 HTML", "html.html#ID-75233634", "document.write(...)")}}{{Spec2("DOM2 HTML")}} 
+ +

תאימות דפדפן

+ + + +

{{Compat("api.Document.write")}}

+ +

ראה גם

+ + diff --git a/files/he/web/api/domstring/index.html b/files/he/web/api/domstring/index.html new file mode 100644 index 0000000000..210e3c86c0 --- /dev/null +++ b/files/he/web/api/domstring/index.html @@ -0,0 +1,50 @@ +--- +title: DOMString +slug: Web/API/DOMString +translation_of: Web/API/DOMString +--- +

{{APIRef("DOM")}}
+ מחרוזת DOMString הינה מחרוזות מסוג UTF-16.
+ כל מחרוזת בשפת JavaScript נחשבת למחרוזת UTF-16 ולכן, נחשבת ל-DOMString באופן אוטומטי.

+ +

מפרט

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebIDL', '#idl-DOMString', 'DOMString')}}{{Spec2('WebIDL')}}Rephrasing of the definition to remove weird edge cases.
{{SpecName('DOM3 Core', 'core.html#DOMString', 'DOMString')}}{{Spec2('DOM3 Core')}}No change from {{SpecName('DOM2 Core')}}
{{SpecName('DOM2 Core', 'core.html#ID-C74D1578', 'DOMString')}}{{Spec2('DOM2 Core')}}No change from {{SpecName('DOM1')}}
{{SpecName('DOM1', 'level-one-core.html#ID-C74D1578', 'DOMString')}}{{Spec2('DOM1')}}Initial definition.
+ +

ראו גם 

+ + diff --git a/files/he/web/api/element/index.html b/files/he/web/api/element/index.html new file mode 100644 index 0000000000..a0d4f8ee21 --- /dev/null +++ b/files/he/web/api/element/index.html @@ -0,0 +1,331 @@ +--- +title: Element +slug: Web/API/Element +tags: + - API + - DOM + - DOM Reference + - Element + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web API +translation_of: Web/API/Element +--- +
{{APIRef("DOM")}}
+ +

Element is the most general base class from which all objects in a {{DOMxRef("Document")}} inherit. It only has methods and properties common to all kinds of elements. More specific classes inherit from Element. For example, the {{DOMxRef("HTMLElement")}} interface is the base interface for HTML elements, while the {{DOMxRef("SVGElement")}} interface is the basis for all SVG elements. Most functionality is specified further down the class hierarchy.

+ +

Languages outside the realm of the Web platform, like XUL through the XULElement interface, also implement Element.

+ +

{{InheritanceDiagram}}

+ +

Properties

+ +

Inherits properties from its parent interface, {{DOMxRef("Node")}}, and by extension that interface's parent, {{DOMxRef("EventTarget")}}. It implements the properties of {{DOMxRef("ParentNode")}}, {{DOMxRef("ChildNode")}}, {{DOMxRef("NonDocumentTypeChildNode")}}, and {{DOMxRef("Animatable")}}.

+ +
+
{{DOMxRef("Element.attributes")}} {{readOnlyInline}}
+
Returns a {{DOMxRef("NamedNodeMap")}} object containing the assigned attributes of the corresponding HTML element.
+
{{DOMxRef("Element.classList")}} {{readOnlyInline}}
+
Returns a {{DOMxRef("DOMTokenList")}} containing the list of class attributes.
+
{{DOMxRef("Element.className")}}
+
Is a {{DOMxRef("DOMString")}} representing the class of the element.
+
{{DOMxRef("Element.clientHeight")}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the inner height of the element.
+
{{DOMxRef("Element.clientLeft")}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the width of the left border of the element.
+
{{DOMxRef("Element.clientTop")}}  {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the width of the top border of the element.
+
{{DOMxRef("Element.clientWidth")}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the inner width of the element.
+
{{DOMxRef("Element.computedName")}} {{readOnlyInline}}
+
Returns a {{DOMxRef("DOMString")}} containing the label exposed to accessibility.
+
{{DOMxRef("Element.computedRole")}} {{readOnlyInline}}
+
Returns a {{DOMxRef("DOMString")}} containing the ARIA role that has been applied to a particular element. 
+
{{DOMxRef("Element.id")}}
+
Is a {{DOMxRef("DOMString")}} representing the id of the element.
+
{{DOMxRef("Element.innerHTML")}}
+
Is a {{DOMxRef("DOMString")}} representing the markup of the element's content.
+
{{DOMxRef("Element.localName")}} {{readOnlyInline}}
+
A {{DOMxRef("DOMString")}} representing the local part of the qualified name of the element.
+
{{DOMxRef("Element.namespaceURI")}} {{readonlyInline}}
+
The namespace URI of the element, or null if it is no namespace. +
+

Note: In Firefox 3.5 and earlier, HTML elements are in no namespace. In later versions, HTML elements are in the http://www.w3.org/1999/xhtml namespace in both HTML and XML trees. {{ gecko_minversion_inline("1.9.2")}}

+
+
+
{{DOMxRef("NonDocumentTypeChildNode.nextElementSibling")}} {{readOnlyInline}}
+
Is an {{DOMxRef("Element")}}, the element immediately following the given one in the tree, or null if there's no sibling node.
+
{{DOMxRef("Element.outerHTML")}}
+
Is a {{DOMxRef("DOMString")}} representing the markup of the element including its content. When used as a setter, replaces the element with nodes parsed from the given string.
+
{{DOMxRef("Element.prefix")}} {{readOnlyInline}}
+
A {{DOMxRef("DOMString")}} representing the namespace prefix of the element, or null if no prefix is specified.
+
{{DOMxRef("NonDocumentTypeChildNode.previousElementSibling")}} {{readOnlyInline}}
+
Is a {{DOMxRef("Element")}}, the element immediately preceding the given one in the tree, or null if there is no sibling element.
+
{{DOMxRef("Element.scrollHeight")}}  {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the scroll view height of an element.
+
{{DOMxRef("Element.scrollLeft")}}
+
Is a {{jsxref("Number")}} representing the left scroll offset of the element.
+
{{DOMxRef("Element.scrollLeftMax")}} {{Non-standard_Inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the maximum left scroll offset possible for the element.
+
{{DOMxRef("Element.scrollTop")}}
+
A {{jsxref("Number")}} representing number of pixels the top of the document is scrolled vertically.
+
{{DOMxRef("Element.scrollTopMax")}} {{Non-standard_Inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the maximum top scroll offset possible for the element.
+
{{DOMxRef("Element.scrollWidth")}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the scroll view width of the element.
+
{{DOMxRef("Element.shadowRoot")}}{{readOnlyInline}}
+
Returns the open shadow root that is hosted by the element, or null if no open shadow root is present.
+
{{DOMxRef("Element.openOrClosedShadowRoot")}} {{Non-standard_Inline}}{{readOnlyInline}}
+
Returns the shadow root that is hosted by the element, regardless if its open or closed. Available only to WebExtensions.
+
{{DOMxRef("Element.slot")}} {{Experimental_Inline}}
+
Returns the name of the shadow DOM slot the element is inserted in.
+
{{DOMxRef("Element.tabStop")}} {{Non-standard_Inline}}
+
Is a {{jsxref("Boolean")}} indicating if the element can receive input focus via the tab key.
+
{{DOMxRef("Element.tagName")}} {{readOnlyInline}}
+
Returns a {{jsxref("String")}} with the name of the tag for the given element.
+
{{DOMxRef("Element.undoManager")}} {{Experimental_Inline}} {{readOnlyInline}}
+
Returns the {{DOMxRef("UndoManager")}} associated with the element.
+
{{DOMxRef("Element.undoScope")}} {{Experimental_Inline}}
+
Is a {{jsxref("Boolean")}} indicating if the element is an undo scope host, or not.
+
+ +
+

Note: DOM Level 3 defined namespaceURI, localName and prefix on the {{DOMxRef("Node")}} interface. In DOM4 they were moved to Element.

+ +

This change is implemented in Chrome since version 46.0 and Firefox since version 48.0.

+
+ +

Properties included from Slotable

+ +

The Element interface includes the following property, defined on the {{DOMxRef("Slotable")}} mixin.

+ +
+
{{DOMxRef("Slotable.assignedSlot")}}{{readonlyInline}}
+
Returns a {{DOMxRef("HTMLSlotElement")}} representing the {{htmlelement("slot")}} the node is inserted in.
+
+ +

Event handlers

+ +
+
{{domxref("Element.onfullscreenchange")}}
+
An event handler for the {{event("fullscreenchange")}} event, which is sent when the element enters or exits full-screen mode. This can be used to watch both for successful expected transitions, but also to watch for unexpected changes, such as when your app is backgrounded.
+
{{domxref("Element.onfullscreenerror")}}
+
An event handler for the {{event("fullscreenerror")}} event, which is sent when an error occurs while attempting to change into full-screen mode.
+
+ +

Obsolete event handlers

+ +
+
{{DOMxRef("Element.onwheel")}}
+
Returns the event handling code for the {{Event("wheel")}} event. This is now implemented on {{DOMxRef("GlobalEventHandlers.onwheel", "GlobalEventHandlers")}}.
+
+ +

Methods

+ +

Inherits methods from its parents {{DOMxRef("Node")}}, and its own parent, {{DOMxRef("EventTarget")}}, and implements those of {{DOMxRef("ParentNode")}}, {{DOMxRef("ChildNode")}}, {{DOMxRef("NonDocumentTypeChildNode")}}, and {{DOMxRef("Animatable")}}.

+ +
+
{{DOMxRef("EventTarget.addEventListener()")}}
+
Registers an event handler to a specific event type on the element.
+
{{DOMxRef("Element.attachShadow()")}}
+
Attatches a shadow DOM tree to the specified element and returns a reference to its {{DOMxRef("ShadowRoot")}}.
+
{{DOMxRef("Element.animate()")}} {{Experimental_Inline}}
+
A shortcut method to create and run an animation on an element. Returns the created Animation object instance.
+
{{DOMxRef("Element.closest()")}} {{Experimental_Inline}}
+
Returns the {{DOMxRef("Element")}} which is the closest ancestor of the current element (or the current element itself) which matches the selectors given in parameter.
+
{{DOMxRef("Element.createShadowRoot()")}} {{Non-standard_Inline}} {{Deprecated_Inline}}
+
Creates a shadow DOM on on the element, turning it into a shadow host. Returns a {{DOMxRef("ShadowRoot")}}.
+
{{DOMxRef("Element.computedStyleMap()")}} {{Experimental_Inline}}
+
Returns a {{DOMxRef("StylePropertyMapReadOnly")}} interface which provides a read-only representation of a CSS declaration block that is an alternative to {{DOMxRef("CSSStyleDeclaration")}}.
+
{{DOMxRef("EventTarget.dispatchEvent()")}}
+
Dispatches an event to this node in the DOM and returns a {{jsxref("Boolean")}} that indicates whether no handler canceled the event.
+
{{DOMxRef("Element.getAnimations()")}} {{Experimental_Inline}}
+
Returns an array of Animation objects currently active on the element.
+
{{DOMxRef("Element.getAttribute()")}}
+
Retrieves the value of the named attribute from the current node and returns it as an {{jsxref("Object")}}.
+
{{DOMxRef("Element.getAttributeNames()")}}
+
Returns an array of attribute names from the current element.
+
{{DOMxRef("Element.getAttributeNS()")}}
+
Retrieves the value of the attribute with the specified name and namespace, from the current node and returns it as an {{jsxref("Object")}}.
+
{{DOMxRef("Element.getAttributeNode()")}} {{Obsolete_Inline}}
+
Retrieves the node representation of the named attribute from the current node and returns it as an {{DOMxRef("Attr")}}.
+
{{DOMxRef("Element.getAttributeNodeNS()")}} {{Obsolete_Inline}}
+
Retrieves the node representation of the attribute with the specified name and namespace, from the current node and returns it as an {{DOMxRef("Attr")}}.
+
{{DOMxRef("Element.getBoundingClientRect()")}}
+
Returns the size of an element and its position relative to the viewport.
+
{{DOMxRef("Element.getClientRects()")}}
+
Returns a collection of rectangles that indicate the bounding rectangles for each line of text in a client.
+
{{DOMxRef("Element.getElementsByClassName()")}}
+
Returns a live {{DOMxRef("HTMLCollection")}} that contains all descendants of the current element that possess the list of classes given in the parameter.
+
{{DOMxRef("Element.getElementsByTagName()")}}
+
Returns a live {{DOMxRef("HTMLCollection")}} containing all descendant elements, of a particular tag name, from the current element.
+
{{DOMxRef("Element.getElementsByTagNameNS()")}}
+
Returns a live {{DOMxRef("HTMLCollection")}} containing all descendant elements, of a particular tag name and namespace, from the current element.
+
{{DOMxRef("Element.hasAttribute()")}}
+
Returns a {{jsxref("Boolean")}} indicating if the element has the specified attribute or not.
+
{{DOMxRef("Element.hasAttributeNS()")}}
+
Returns a {{jsxref("Boolean")}} indicating if the element has the specified attribute, in the specified namespace, or not.
+
{{DOMxRef("Element.hasAttributes()")}}
+
Returns a {{jsxref("Boolean")}} indicating if the element has one or more HTML attributes present.
+
{{DOMxRef("Element.hasPointerCapture()")}}
+
Indicates whether the element on which it is invoked has pointer capture for the pointer identified by the given pointer ID.
+
{{DOMxRef("Element.insertAdjacentElement()")}}
+
Inserts a given element node at a given position relative to the element it is invoked upon.
+
{{DOMxRef("Element.insertAdjacentHTML()")}}
+
Parses the text as HTML or XML and inserts the resulting nodes into the tree in the position given.
+
{{DOMxRef("Element.insertAdjacentText()")}}
+
Inserts a given text node at a given position relative to the element it is invoked upon.
+
{{DOMxRef("Element.matches()")}} {{Experimental_Inline}}
+
Returns a {{jsxref("Boolean")}} indicating whether or not the element would be selected by the specified selector string.
+
{{DOMxRef("Element.querySelector()")}}
+
Returns the first {{DOMxRef("Node")}} which matches the specified selector string relative to the element.
+
{{DOMxRef("Element.querySelectorAll()")}}
+
Returns a {{DOMxRef("NodeList")}} of nodes which match the specified selector string relative to the element.
+
{{DOMxRef("Element.releasePointerCapture()")}}
+
Releases (stops) pointer capture that was previously set for a specific {{DOMxRef("PointerEvent","pointer event")}}.
+
{{DOMxRef("ChildNode.remove()")}} {{Experimental_Inline}}
+
Removes the element from the children list of its parent.
+
{{DOMxRef("Element.removeAttribute()")}}
+
Removes the named attribute from the current node.
+
{{DOMxRef("Element.removeAttributeNS()")}}
+
Removes the attribute with the specified name and namespace, from the current node.
+
{{DOMxRef("Element.removeAttributeNode()")}} {{Obsolete_Inline}}
+
Removes the node representation of the named attribute from the current node.
+
{{DOMxRef("EventTarget.removeEventListener()")}}
+
Removes an event listener from the element.
+
{{DOMxRef("Element.requestFullscreen()")}} {{Experimental_Inline}}
+
Asynchronously asks the browser to make the element full-screen.
+
{{DOMxRef("Element.requestPointerLock()")}} {{Experimental_Inline}}
+
Allows to asynchronously ask for the pointer to be locked on the given element.
+
+ +
+
{{domxref("Element.scroll()")}}
+
Scrolls to a particular set of coordinates inside a given element.
+
{{domxref("Element.scrollBy()")}}
+
Scrolls an element by the given amount.
+
{{DOMxRef("Element.scrollIntoView()")}} {{Experimental_Inline}}
+
Scrolls the page until the element gets into the view.
+
{{domxref("Element.scrollTo()")}}
+
Scrolls to a particular set of coordinates inside a given element.
+
{{DOMxRef("Element.setAttribute()")}}
+
Sets the value of a named attribute of the current node.
+
{{DOMxRef("Element.setAttributeNS()")}}
+
Sets the value of the attribute with the specified name and namespace, from the current node.
+
{{DOMxRef("Element.setAttributeNode()")}} {{Obsolete_Inline}}
+
Sets the node representation of the named attribute from the current node.
+
{{DOMxRef("Element.setAttributeNodeNS()")}} {{Obsolete_Inline}}
+
Sets the node representation of the attribute with the specified name and namespace, from the current node.
+
{{DOMxRef("Element.setCapture()")}} {{Non-standard_Inline}}
+
Sets up mouse event capture, redirecting all mouse events to this element.
+
{{DOMxRef("Element.setPointerCapture()")}}
+
Designates a specific element as the capture target of future pointer events.
+
{{DOMxRef("Element.toggleAttribute()")}}
+
Toggles a boolean attribute, removing it if it is present and adding it if it is not present, on the specified element.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Web Animations", '', '')}}{{Spec2("Web Animations")}}Added the getAnimations() method.
{{SpecName('Undo Manager', '', 'Element')}}{{Spec2('Undo Manager')}}Added the undoScope and undoManager properties.
{{SpecName('Pointer Events 2', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('Pointer Events 2')}}Added the following event handlers: ongotpointercapture and onlostpointercapture.
+ Added the following methods: setPointerCapture() and releasePointerCapture().
{{SpecName('Pointer Events', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('Pointer Events')}}Added the following event handlers: ongotpointercapture and onlostpointercapture.
+ Added the following methods: setPointerCapture() and releasePointerCapture().
{{SpecName('Selectors API Level 1', '#interface-definitions', 'Element')}}{{Spec2('Selectors API Level 1')}}Added the following methods: querySelector() and querySelectorAll().
{{SpecName('Pointer Lock', 'index.html#element-interface', 'Element')}}{{Spec2('Pointer Lock')}}Added the requestPointerLock() method.
{{SpecName('Fullscreen', '#api', 'Element')}}{{Spec2('Fullscreen')}}Added the requestFullscreen() method.
{{SpecName('DOM Parsing', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('DOM Parsing')}}Added the following properties: innerHTML, and outerHTML.
+ Added the following method: insertAdjacentHTML().
{{SpecName('CSSOM View', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('CSSOM View')}}Added the following properties: scrollTop, scrollLeft, scrollWidth, scrollHeight, clientTop, clientLeft, clientWidth, and clientHeight.
+ Added the following methods: getClientRects(), getBoundingClientRect(), scroll()scrollBy(), scrollTo() and scrollIntoView().
{{SpecName('Element Traversal', '#ecmascript-bindings', 'Element')}}{{Spec2('Element Traversal')}}Added inheritance of the {{DOMxRef("ElementTraversal")}} interface.
{{SpecName('DOM WHATWG', '#interface-element', 'Element')}}{{Spec2('DOM WHATWG')}}Added the following methods: closest(), insertAdjacentElement() and insertAdjacentText().
+ Moved hasAttributes() from the Node interface to this one.
{{SpecName("DOM4", "#interface-element", "Element")}}{{Spec2("DOM4")}}Removed the following methods: setIdAttribute(), setIdAttributeNS(), and setIdAttributeNode().
+ Modified the return value of getElementsByTagName() and getElementsByTagNameNS().
+ Removed the schemaTypeInfo property.
{{SpecName('DOM3 Core', 'core.html#ID-745549614', 'Element')}}{{Spec2('DOM3 Core')}}Added the following methods: setIdAttribute(), setIdAttributeNS(), and setIdAttributeNode(). These methods were never implemented and have been removed in later specifications.
+ Added the schemaTypeInfo property. This property was never implemented and has been removed in later specifications.
{{SpecName('DOM2 Core', 'core.html#ID-745549614', 'Element')}}{{Spec2('DOM2 Core')}}The normalize() method has been moved to {{DOMxRef("Node")}}.
{{SpecName('DOM1', 'level-one-core.html#ID-745549614', 'Element')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.Element")}}

diff --git a/files/he/web/api/geolocation/index.html b/files/he/web/api/geolocation/index.html new file mode 100644 index 0000000000..e69c21503d --- /dev/null +++ b/files/he/web/api/geolocation/index.html @@ -0,0 +1,109 @@ +--- +title: Geolocation +slug: Web/API/Geolocation +tags: + - API + - Advanced + - Geolocation API + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/Geolocation +--- +
+ {{APIRef}}
+

The Geolocation interface represents an object able to programmatically obtain the position of the device. It gives Web content access to the location of the device. This allows a Web site or app offer customized results based on the user's location.

+

An object with this interface is obtained using the {{domxref("NavigatorGeolocation.geolocation")}} property implemented by the {{domxref("Navigator")}} object.

+
+

Note: For security reasons, when a web page tries to access location information, the user is notified and asked to grant permission. Be aware that each browser has its own policies and methods for requesting this permission.

+
+

Properties

+

The Geolocation interface neither implements, nor inherit any property.

+

Methods

+

The Geolocation interface doesn't inherit any method.

+
+
+ {{domxref("Geolocation.getCurrentPosition()")}}
+
+ Determines the device's current location and gives back a {{domxref("Position")}} object with the data.
+
+ {{domxref("Geolocation.watchPosition()")}}
+
+ Returns a long value representing the newly established callback function to be invoked whenever the device location changes.
+
+ {{domxref("Geolocation.clearWatch()")}}
+
+ Removes the particular handler previously installed using watchPosition().
+
+

Specifications

+ + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation')}}{{Spec2('Geolocation')}}Initial specification.
+

Browser compatibility

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5{{CompatGeckoDesktop("1.9.1")}}910.60
+ Removed in 15.0
+ Reintroduced in 16.0
5
+
+
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown()}}{{CompatUnknown()}}{{CompatGeckoMobile("4")}}{{CompatUnknown()}}10.60{{CompatUnknown()}}
+
+

See also

+ diff --git "a/files/he/web/api/geolocation/\327\236\327\236\327\251\327\247_\327\251\327\231\327\250\327\225\327\252\327\231_\327\236\327\231\327\247\327\225\327\235/index.html" "b/files/he/web/api/geolocation/\327\236\327\236\327\251\327\247_\327\251\327\231\327\250\327\225\327\252\327\231_\327\236\327\231\327\247\327\225\327\235/index.html" new file mode 100644 index 0000000000..f87dbb0f0b --- /dev/null +++ "b/files/he/web/api/geolocation/\327\236\327\236\327\251\327\247_\327\251\327\231\327\250\327\225\327\252\327\231_\327\236\327\231\327\247\327\225\327\235/index.html" @@ -0,0 +1,250 @@ +--- +title: ממשק שירותי מיקום +slug: Web/API/Geolocation/ממשק_שירותי_מיקום +translation_of: Web/API/Geolocation_API +--- +

ממשק שירותי המיקום, geolocation API, מאפשר למשתמש לשתף את המיקום שלו עם אפליקציות ברשת. כדי להגן על הפרטיות, המשתמש נדרש להסכים לשתף את שירותי המיקום שלו.

+

אובייקט ה- geolocation 

+

ממשק שירותי המיקום נגיש באמצעות אובייקט:{{domxref("window.navigator.geolocation","navigator.geolocation")}} .

+

אם האובייקט קיים, ממשק שירותי המיקום נתמך: ניתן לבדוק אם ממשק שירותי המיקום נתמך באמצעות: 

+
if ("geolocation" in navigator) {
+  /* הממשק נתמך*/
+} else {
+  /* הממשק אינו נתמך */
+}הערה
+
+
+

הערה: מגרסה מס' 24 של FireFox ומטה, הפקודה geolocation" in navigator" מחזירה true אפילו אם הממשק אינו נתמך. באג זה תוקן בגרסה 25 של FireFox על מנת לעמוד בתקן. ({{bug(884921)}}).

+
+

קבלת המיקום הנוכחי

+

כדי לקבל את נתוני המיקום הנוכחי של המשתמש, ניתן לקרוא לפונקציה:  {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}}. הפונקציה יוצרת קריאה אסינכרונית על מנת לאחזר את המיקום של המשתמש ובודקת את החומרה על מנת לקבל את המיקום העדכני ביותר. כאשר נתוני המיקום חוזרים כתוצאה מהקריאה, פונקציית המטרה (באנגלית: callback) נקראת. אפשר להעביר לקריאה פרמטר נוסף, פרמטר שני: פונקציית מטרה לטיפול במיקרה של שגיאה. אפשר להעביר פרמטר שלישי לקריאה: אובייקט options שבו אפשר להגדיר מהו הוותק המכסימלי לערכי המיקום המוחזרים, משך הזמן המכסימלי להמתנה עד שנתוני המיקום יתקבלו ורמת הדיוק של נתוני המיקום. 

+
+

הערה: כברירת מחדל, הפונקציה, {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}} מנסה להחזיר את נתוני המיקום במהירות האפשרית, אך ברמת דיוק מינימלית. צורה זו שימושית אם רוצים לקבל את הנתונים במהירות הגבוהה האפשרית תוך התפשרות על רמת הדיוק. במכשירים עם מנגנון GPS משך הזמן לקבלת נתונים יכול לקחת דקה ויותר, לכן הפונקציה  {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}} יכולה לקבל בחזרה נתונים שיש בהם מידה מסוימת של שגיאה (אם המיקום חושב על בסיס כתובת IP על בסיס מיקום נקודת wifi).

+
+
navigator.geolocation.getCurrentPosition(function(position) {
+  do_something(position.coords.latitude, position.coords.longitude);
+});
+

הקוד בדוגמא שלעיל יגרום לפונקצייה, ()do_something, להתבצע כאשר נתוני המיקום חזרו.

+

 

+

מעקב אחר המיקום הנוכחי

+

אם נתוני המיקום משתנים (בגלל שהדפדפן נמצא בתנועה, או אם הגיעו נתוני מיקום מדוייקים יותר), אפשר להגדיר פונקציית מטרה (באנגלית: callback), המקבלת נתוני מיקום מעודכנים יותר. עושים זאת באמצעות הפונקציה: {{domxref("window.navigator.geolocation.watchPosition()","watchPosition()")}} שיש לה את אותם פרמטרים כמו הפונקציה:  {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}}. פונקציית המטרה מתבצעת מס' כלשהו של פעמים ומאפשרת לדפדפן לעדכן את המיקום של המשתמש תוך כדי תנועה, או לעדכן את מיקומו בנתונים מעודכנים יותר שהגיעו על ידי טכניקות זיהוי מיקום מדוייקות יותר. ניתן להגדיר פונקציית מטרה נוספת למקרה של שגיאה שתיקרא בכל פעם שתתרחש שגיאה כפי שקורה במיקרה של:  {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}}.

+
+

הערה: ניתן להשתמש בפונקציה: {{domxref("window.navigator.geolocation.watchPosition()","watchPosition()")}} מבלי צורך לקרוא לפני כן לפונקציה: {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}} .

+
+
var watchID = navigator.geolocation.watchPosition(function(position) {
+  do_something(position.coords.latitude, position.coords.longitude);
+});
+

הפונקציה {{domxref("window.navigator.geolocation.watchPosition()","watchPosition()")}} מחזירה id שמזהה את הפונקציה שעוקבת אחר המיקום. ניתן לאחר מכן להשתמש בו כדי לקרוא לפונקציה  {{domxref("window.navigator.geolocation.clearWatch()","clearWatch()")}} על מנת להפסיק את פעולת המעקב אחרי תנועת המשתמש.

+
navigator.geolocation.clearWatch(watchID);
+
+

כיול התוצאות

+

הן הפונקציה {{domxref("window.navigator.geolocation.getCurrentPosition()","getCurrentPosition()")}} והן הפונקציה {{domxref("window.navigator.geolocation.watchPosition()","watchPosition()")}} מקבלות פרמטר פונקציית מטרה למקרה הצלחה בקבלת נתונים, מקבלות פרמטר אופציונאלי למקרה של שגיאה בקבלת נתוני מיקום ופרמטר אופציונאלי שלישי: אובייקט  PositionOptions.

+

{{page("/en-US/docs/DOM/window.navigator.geolocation.getCurrentPosition","PositionOptions")}}

+

קריאה ל: {{domxref("window.navigator.geolocation.watchPosition()","watchPosition")}} יכולה להיראות כך:

+
function geo_success(position) {
+  do_something(position.coords.latitude, position.coords.longitude);
+}
+
+function geo_error() {
+  alert("Sorry, no position available.");
+}
+
+var geo_options = {
+  enableHighAccuracy: true,
+  maximumAge        : 30000,
+  timeout           : 27000
+};
+
+var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);
+

A demo of watchPosition in use: http://www.thedotproduct.org/experiments/geo/
+ 

+

נתוני המיקום

+

המיקום של המשתמש הוא אובייקט Position שמכיל בתוכו אובייקט Coordinates.

+

{{page("/en-US/docs/DOM/window.navigator.geolocation.getCurrentPosition","Position")}}

+

{{page("/en-US/docs/DOM/window.navigator.geolocation.getCurrentPosition","Coordinates")}}

+

טיפול בשגיאות

+

פונקציית המטרה לטיפול בשגיאות נגישה גם בקריאה לפונקציה ()getCurrentPosition וגם בקריאה ל ()watchPositionומקבלת כפרמטר ראשון אובייקט PositionError

+
function errorCallback(error) {
+  alert('ERROR(' + error.code + '): ' + error.message);
+};
+
+

{{page("/en-US/docs/DOM/window.navigator.geolocation.getCurrentPosition","PositionError")}}

+

דוגמא שלמה לממשק שירותי מיקום

+ +

HTML: 

+
<p><button onclick="geoFindMe()">Show my location</button></p>
+<div id="out"></div>
+
+

JavaScript:

+
function geoFindMe() {
+  var output = document.getElementById("out");
+
+  if (!navigator.geolocation){
+    output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
+    return;
+  }
+
+  function success(position) {
+    var latitude  = position.coords.latitude;
+    var longitude = position.coords.longitude;
+
+    output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
+
+    var img = new Image();
+    img.src = "http://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
+
+    output.appendChild(img);
+  };
+
+  function error() {
+    output.innerHTML = "Unable to retrieve your location";
+  };
+
+  output.innerHTML = "<p>Locating…</p>";
+
+  navigator.geolocation.getCurrentPosition(success, error);
+}
+
+

תוצאות של הדוגמא לעיל:

+

{{ EmbedLiveSample('Geolocation_Live_Example',350,410) }}

+

הצגת הודעה לבקשת רשות

+

כל תוסף המשתייך ל addons.mozilla.org המשתמש בממשק שירותי המיקום חייב לקבל אישור מהמשתמש לגשת לממשק על ידי בקשת רשות מפורשת. הפונקציה הבאה תבקש אישור באופן שזהה לבקשת האישור המוצגת לדפים ברשת. הבחירה של המשתמש תישמר בהעדפות באמצעות פרמטר pref או הוא מאופשר. הפונקציה המוצבעת על ידי פרמטר callback תיקרא עם פרמטר בוליאני המציין את בחירת המשתמש. אם הערך true יש לתוסף הרשאה לגשת לנתוני המיקום. 

+
function prompt(window, pref, message, callback) {
+    let branch = Components.classes["@mozilla.org/preferences-service;1"]
+                           .getService(Components.interfaces.nsIPrefBranch);
+
+    if (branch.getPrefType(pref) === branch.PREF_STRING) {
+        switch (branch.getCharPref(pref)) {
+        case "always":
+            return callback(true);
+        case "never":
+            return callback(false);
+        }
+    }
+
+    let done = false;
+
+    function remember(value, result) {
+        return function() {
+            done = true;
+            branch.setCharPref(pref, value);
+            callback(result);
+        }
+    }
+
+    let self = window.PopupNotifications.show(
+        window.gBrowser.selectedBrowser,
+        "geolocation",
+        message,
+        "geo-notification-icon",
+        {
+            label: "Share Location",
+            accessKey: "S",
+            callback: function(notification) {
+                done = true;
+                callback(true);
+            }
+        }, [
+            {
+                label: "Always Share",
+                accessKey: "A",
+                callback: remember("always", true)
+            },
+            {
+                label: "Never Share",
+                accessKey: "N",
+                callback: remember("never", false)
+            }
+        ], {
+            eventCallback: function(event) {
+                if (event === "dismissed") {
+                    if (!done) callback(false);
+                    done = true;
+                    window.PopupNotifications.remove(self);
+                }
+            },
+            persistWhileVisible: true
+        });
+}
+
+prompt(window,
+       "extensions.foo-addon.allowGeolocation",
+       "Foo Add-on wants to know your location.",
+       function callback(allowed) { alert(allowed); });
+
+

תאימות דפדפנים

+
+ {{ CompatibilityTable() }}
+
+  
+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5{{CompatGeckoDesktop("1.9.1")}}910.60
+ Removed in 15.0
+ Reintroduced in 16.0
5
+
+
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown()}}{{CompatUnknown()}}{{CompatGeckoMobile("4")}}1.0.1{{CompatUnknown()}}10.60
+ Removed in 15.0
+ Reintroduced in 16.0
{{CompatUnknown()}}
+
+

הערות לגבי Gecko

+

דפדפן FireFox תומך בקבלת נתוני המיקום בהתבסס על מידע WiFi באמצעות שירותי המיקום של גוגל. בטרנזאקציה שבין FireFox ל Google, המידע שמועבר כולל מידע על נקודת הגישה ל WiFi, כולל access token (שדומה לcookie בעלת תוקף למשך שבועיים) וכולל את כתובת ה IP של המשתמש. למידע נוסף יש התעדכן בתנאי הפרטיות של Mozilla ובתנאי הפרטיות של גוגל המפרטים באיזה אופן נתונים אלה ניתנים לשימוש. 

+

FireFox גרסת 3.6 (Gecko 1.9.2) הוסיף תמיכה לשימוש בשירות GPSD (GPS daemon) בשביל שירותי מיקום עבור Linux. 

+

לעיון נוסף

+ diff --git a/files/he/web/api/index.html b/files/he/web/api/index.html new file mode 100644 index 0000000000..83cde65af8 --- /dev/null +++ b/files/he/web/api/index.html @@ -0,0 +1,38 @@ +--- +title: Web API Interfaces +slug: Web/API +tags: + - API + - Apps + - JavaScript + - Landing + - Reference + - Web + - WebAPI +translation_of: Web/API +--- +

כשאתה כותב קוד עבור ה-Web, יש הרבה Web APIs זמינים. להלן רשימה של כל ה-APIs והממשקים (טיפוסי עצמים) בהם תוכל להשתמש בעת פיתוח אפליקציית ה-Web או האתר שלך.

+ +
בדרך כלל משתמשים ב-Web APIs עם JavaScript, אם כי זה לא תמיד חייב להיות כך.
+ +
+ +

מפרטים

+ +

זו רשימת כל ה-APIs הזמינים.

+ +

{{ListGroups}}

+ +

ממשקים

+ +

זו רשימת כל הממשקים (זאת אומרת, טיפוסים של עצמים) הזמינים.

+ +

{{APIListAlpha}}

+ +

ראה גם

+ + + + diff --git a/files/he/web/api/indexeddb_api/browser_storage_limits_and_eviction_criteria/index.html b/files/he/web/api/indexeddb_api/browser_storage_limits_and_eviction_criteria/index.html new file mode 100644 index 0000000000..094ee01378 --- /dev/null +++ b/files/he/web/api/indexeddb_api/browser_storage_limits_and_eviction_criteria/index.html @@ -0,0 +1,141 @@ +--- +title: מגבלות האחסנה של הדפדפן וקריטריונים לפינוי +slug: Web/API/IndexedDB_API/Browser_storage_limits_and_eviction_criteria +tags: + - Database + - IndexedDB + - LRU + - אחסנה + - בדיס נתונים + - מגבלה + - פינוי + - צד הלקוח +translation_of: Web/API/IndexedDB_API/Browser_storage_limits_and_eviction_criteria +--- +
{{DefaultAPISidebar("IndexedDB")}}
+ +
קיימות מספר טכנולוגיות רשת המאחסנות נתונים מסוג זה או אחר בצד הלקוח (כלומר, על הדיסק המקומי שלך). התהליך בו הדפדפן מחשב כמה מקום להקצות לאחסנת מידע רשת ומה למחוק כאשר מגיעים לגבול אינו פשוט, ונבדל בין דפדפנים.
+ +
מאמר זה מתאר איך דפדפנים מכריעים איזה תוכן מקומי לטהר, ומתי בסדר לשחרר חלל אחסנה מקומי.
+ +

+ +
+

לתשומת לבך: המידע שלהלן אמור להיות מדוייק במידה מספקת עבור רוב הדפדפנים המודרניים, אך פרטי דפדפן נקראים כאשר ידועים. אופרה וכרום צריכים לפעול באותה דרך בכל המקרים, Opera Mini (תצוגת צד שרת, שעדיין מבוסס על תגובה מהירה) אינו מאחסן כל נתונים שהם בצד הלדוח.

+
+ +

אלו טכנולוגיות משתמשות באחסנת הנתונים של הדפדפן?

+ +

בפיירפוקס, הטכנולוגיות הבאות עושות שימוש באחסנת הנתונים של הדפדפן לאחסן נתונים כאשר יש צורך.  הגדרנו עבורם את המושג "לקוחות מכסה" בהקשר זה:

+ + + +
+

לתשומת לבך: בפיירפוקס, אחסנת הרשת בקרוב תתחיל להשתמש גם היא באותם כלי ניהול שטחי אחסון , כמתואר במסמך זה.

+
+ +
+

לתשומת לבך: במצב גלישה פרטית, רוב אחסנת המידע אינה נתמכת. נתוני אחסון מקומיים ועוגיות עדיין מאוחסנים, אך הם ארעיים - הנתונים נמחקים כאשר סוגרים את חלון אך הם ארעיים — הנתונים נמחקים עם סגירת חלון הגלישה הפרטית האחרון.

+
+ +

"זמן הגישה האחרון" של מקורות מתעדכן כאשר כל אחד מאלה מופעל/מושבת  — פינוי מקורות ימח' נתונים עבור כל לקוחות המכסה.

+ +

בכרום/אופרה, ממשק פיתוח היישומים של ניהול המכסות מטפל בניהול עבור  AppCache, IndexedDB, WebSQL, ו-File System API.

+ +

טיפוסים שונים של אחסנת נתונים

+ +

גם באותו הדפדפן, שימוש באותה שיטת אחסון, קיינות מחלקות שונות של אחסנת נתונים להבין. פרק זה ידון במפר מהם שייתכן ויימצאו בדפדפנים שונים.

+ +

אחסנה מופיעה במספר טיפוסים:

+ + + +

בפיירפוקס, כשאשר נעשה שימוש באחסנה קבועה,, ניתן למשתמש/ת חלון ממשק משתמש קופץ להתריע לו/ה כי הנתונים יישמרו, ובחלון תישאל השאלה אם המשתמש/ת מסכים/ה לכך.  אחסנת נתונים זמנית אינה מעוררת כל פנייה למשתמש/ת.

+ +

כברירת מחדל האחסנה היא זמנית; מפתחים יכולים לבחור להשתמש באחסנה קבועה לאתרים שלהם באמצעות השיטה  {{domxref("StorageManager.persist()")}} הזמינה ב-Storage API.

+ +

היכן מאוחסנים הנתונים?

+ +

כל טיפוס אחסנה מייצג מאגר נפרד. להלן המיפוי האקטואלי ל,תיקיות תחת פרופיל הפיירפוקס של  המשתמש/ת (דפדפנים אחרים עשויים להיות מעט שונים):

+ + + +
+
+

לתשומת לבך: אחרי שהוצג ה Storage API, התיקייה "permanent" יכולה להיחשב  מיושנת; התיקייה  "permanent" מאחסנת רק את בסיסי הנתונים מהטיפוס הקבוע IndexedDB. לא משנה אם מצב התיבה הוא  "best-effort" או "persistent" — נתונים   נשמרים תחת <profile>/storage/default.

+
+
+ +
+

לתשומת לבך: בפיירפוקס , ניתן למצוא את תיקיית הפרופיל שלך על ידי הכנסת  about:support בשורת ה- URL , ולחיצה על הכפתור  פתיחת ספרייה  (למשל Show ב- Finder על Mac OS X) על יד הכותרת Profile Folder .

+
+ +
+

לתשומת לבך: אם תחפשו במידע השמור בתיקיית הפרופיל , ייתכן שתמצאו תיקייה רביעית:: persistent. בעיקרות, שמה של התיקייה persistent שונה ל-permanent בשלב מסויים בעבר  כדי ששדרוגים/מעברים יהיו פשוטים לביצוע.

+
+ +
+

לתשומת לבך: אל למשתמשים להוסיף תיקיות וקבצים משלהם תחת  <profile>/storage. זה יגרום לאתחולי אחסנה להיכשל; לדוגמא, {{domxref("IDBFactory.open()", "open()")}} יגרום לאירוע שגיאה.

+
+ +

מגבלות האחסנה

+ +

שטח האחסנה המירבי של הדפדפן הוא דינמי — הוא מבוסס על גודל הדיסק הקשיח.  הגבול הגלובלי מחושב כ-50% מהשטח הפנוי על הדיסק. בפיירפוקס, כלי פנימי של הדפדפן הקרוי   Quota Manager כוקב אחרי גודל חלל הדיסק שכל מקור מנצל עד תום, ומוחק נתונים אם יש צורך בכך.

+ +

כך שאם נפח הדיסק הקשיח שלך הוא 500 ג"ב, אזי שטח האחסון לדפדפן הינו 250 ג"ב. במקרה של חריגה, מופעל תהליך בשם origin eviction, המוחק את כל שווי הנתונים של המקור  עד שכמות הנתונים המאוחסנת חוזרת אל מתחת לגבול. אין כל אפקט של קיצוץ הבא למחוק חלקים של מקורות  — מחיקת בסיס נתונים של מקור עלולה ליצור בעיות של חוסר עקביות.

+ +

קיים גם גבול הקרוי group limit — הוא מוגדר כ- 20% מהגבול הגלובלי, אך יש לו מינימום של 10 מ"ב ומקסימום של 2 ג"ב. כל מקור הוא חלק מקבוצה (קבוצת מקורות). קיימת קבוצה לכל דומיין eTLD+1. לדוגמה:

+ + + +

בקבוצה זו, mozilla.org, www.mozilla.org, ו-joe.blogs.mozilla.org יכולים במצטבר להשתמש במקסימום  20% מהגבול הגלובלי. ל- firefox.com יש מקסימום בנפרד של 20%.

+ +

שני הגבולות מגיבים בצורה שונה כשמגיעים לגבול:

+ + + +
+

לתשומת לבך: הגבול הקבוצתי אינו יכול להיות יותר מהגבול הגלובלי, , למרות מינימום הגבול הקבוצתי הנזכר לעיל . אם הינך במצב של מעט זיכרון באמת כשנניח שהגבול הגלובלי הוא, 8 מ"ב, אז גם הגבול הקבוצתי יהיה  8 מ"ב.

+
+ +
+

לתשומת לבך: כאשר חורגים מהגבול הקבוצתי, או אם פינוי המקור אינו יכול לשחרר מספיק שטח, הדפדפן יצא עם החריגה QuotaExceededError.

+
+ +
+

לתשומת לבך: בכרום מכסת האחסנה הרכה והקשה השתנתה מאז  M66. מידע נוסף ניתן למצוא כאן.

+
+ +

מדיניותLRU

+ +

כאשר שטח הדיסק מתמלא עד תום, מנהל המכסות מתחיל לנקות נתונים בהתבסס על מדיניות  LRU  — המקור בו נעשה שימוש רחוק ביותר מלאחרונה ימחק קודם, ואחר כך זה הבא אחריו, עד שהדפדפן כבר אינו חורג מהגבול.

+ +

אנו עוקבים אחרי "זמן הגישה האחרון" עבור כל מקור באמצעות אחסנה זמנית. כאשר מושג הגבול הגלובלי עבור אחסנה זמנית (עוד אודות הגבול מאוחר יותר), אנו מנסים למצוא את כל המקורות שלא היו בשימוש (iכלומר אלה ללא לשוניות.ישומים פתוחים הממשיכים לשמור מאגרי מידע פתוחים). אלה ממויינים בשלב זה על פי "זמן הגישה האחרון".  המקור שהיה בשימוש הכי רחוק מלאחרונה נמחקים בשלב זה  עד שיש מספיק מקום להגשים את הבקשה שגרמה לפינוי המקור.

+ +

ראו גם

+ + diff --git a/files/he/web/api/indexeddb_api/index.html b/files/he/web/api/indexeddb_api/index.html new file mode 100644 index 0000000000..957b6f96c5 --- /dev/null +++ b/files/he/web/api/indexeddb_api/index.html @@ -0,0 +1,165 @@ +--- +title: IndexedDB API +slug: Web/API/IndexedDB_API +tags: + - API + - Advanced + - Database + - IndexedDB + - Landing + - NeedsTranslation + - Reference + - Storage + - TopicStub +translation_of: Web/API/IndexedDB_API +--- +
{{DefaultAPISidebar("IndexedDB")}}
+ +

IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this data. While Web Storage is useful for storing smaller amounts of data, it is less useful for storing larger amounts of structured data. IndexedDB provides a solution. This is the main landing page for MDN's IndexedDB coverage — here we provide links to the full API reference and usage guides, browser support details, and some explanation of key concepts.

+ +

{{AvailableInWorkers}}

+ +
+

Note: IndexedDB API is powerful, but may seem too complicated for simple cases. If you'd prefer a simple API, try libraries such as localForage, dexie.js, ZangoDB, PouchDB, idb, idb-keyval, JsStore and lovefield that make IndexedDB more programmer-friendly.

+
+ +

Key concepts and usage

+ +

IndexedDB is a transactional database system, like an SQL-based RDBMS. However, unlike SQL-based RDBMSes, which use fixed-column tables, IndexedDB is a JavaScript-based object-oriented database. IndexedDB lets you store and retrieve objects that are indexed with a key; any objects supported by the structured clone algorithm can be stored. You need to specify the database schema, open a connection to your database, and then retrieve and update data within a series of transactions.

+ + + +
+

Note: Like most web storage solutions, IndexedDB follows a same-origin policy. So while you can access stored data within a domain, you cannot access data across different domains.

+
+ +

Synchronous and asynchronous

+ +

Operations performed using IndexedDB are done asynchronously, so as not to block applications. IndexedDB originally included both synchronous and asynchronous APIs. The synchronous API was intended for use only with Web Workers but was removed from the spec because it was unclear whether it was needed. However, the synchronous API may be reintroduced if there is enough demand from web developers.

+ +

Storage limits and eviction criteria

+ +

There are a number of web technologies that store data of one kind or another on the client side (i.e. on your local disk). IndexedDB is most commonly talked about. The process by which the browser works out how much space to allocate to web data storage and what to delete when that limit is reached is not simple, and differs between browsers. Browser storage limits and eviction criteria attempts to explain how this works, at least in the case of Firefox.

+ +

Interfaces

+ +

To get access to a database, call open() on the indexedDB attribute of a window object. This method returns an {{domxref("IDBRequest")}} object; asynchronous operations communicate to the calling application by firing events on {{domxref("IDBRequest")}} objects.

+ +

Connecting to a database

+ +
+
{{domxref("IDBEnvironment")}}
+
Provides access to IndexedDB functionality. It is implemented by the {{domxref("window")}} and {{domxref("worker")}} objects. This interface isn't part of the 2.0 specification.
+
{{domxref("IDBFactory")}}
+
Provides access to a database. This is the interface implemented by the global object {{domxref("WindowOrWorkerGlobalScope/indexedDB", "indexedDB")}} and is therefore the entry point for the API.
+
{{domxref("IDBOpenDBRequest")}}
+
Represents a request to open a database.
+
{{domxref("IDBDatabase")}}
+
Represents a connection to a database. It's the only way to get a transaction on the database.
+
+ +

Retrieving and modifying data

+ +
+
{{domxref("IDBTransaction")}}
+
Represents a transaction. You create a transaction on a database, specify the scope (such as which object stores you want to access), and determine the kind of access (read only or readwrite) that you want.
+
{{domxref("IDBRequest")}}
+
Generic interface that handles database requests and provides access to results.
+
{{domxref("IDBObjectStore")}}
+
Represents an object store that allows access to a set of data in an IndexedDB database, looked up via primary key.
+
{{domxref("IDBIndex")}}
+
Also allows access to a subset of data in an IndexedDB database, but uses an index to retrieve the record(s) rather than the primary key. This is sometimes faster than using {{domxref("IDBObjectStore")}}.
+
{{domxref("IDBCursor")}}
+
Iterates over object stores and indexes.
+
{{domxref("IDBCursorWithValue")}}
+
Iterates over object stores and indexes and returns the cursor's current value.
+
{{domxref("IDBKeyRange")}}
+
Defines a key range that can be used to retrieve data from a database in a certain range.
+
{{domxref("IDBLocaleAwareKeyRange")}} {{Non-standard_inline}}
+
Defines a key range that can be used to retrieve data from a database in a certain range, sorted according to the rules of the locale specified for a certain index (see createIndex()'s optionalParameters.). This interface isn't part of the 2.0 specification.
+
+ +

Custom event interfaces

+ +

This specification fires events with the following custom interface:

+ +
+
{{domxref("IDBVersionChangeEvent")}}
+
The IDBVersionChangeEvent interface indicates that the version of the database has changed, as the result of an {{domxref("IDBOpenDBRequest.onupgradeneeded")}} event handler function.
+
+ +

Obsolete interfaces

+ +

An early version of the specification also defined the following, now removed, interfaces. They are still documented in case you need to update previously written code:

+ +
+
{{domxref("IDBVersionChangeRequest")}} {{obsolete_inline}}
+
Represents a request to change the version of a database. The way to change the version of the database has since changed (by calling {{domxref("IDBFactory.open")}} without also calling {{domxref("IDBDatabase.setVersion")}}), and the interface {{domxref("IDBOpenDBRequest")}} now has the functionality of the removed {{domxref("IDBVersionChangeRequest")}}.
+
{{domxref("IDBDatabaseException")}}  {{obsolete_inline}}
+
Represents exception conditions that can be encountered while performing database operations.
+
{{domxref("IDBTransactionSync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBTransaction")}}.
+
{{domxref("IDBObjectStoreSync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBObjectStore")}}.
+
{{domxref("IDBIndexSync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBIndex")}}.
+
{{domxref("IDBFactorySync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBFactory")}}.
+
{{domxref("IDBEnvironmentSync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBEnvironment")}}.
+
{{domxref("IDBDatabaseSync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBDatabase")}}.
+
{{domxref("IDBCursorSync")}} {{obsolete_inline}}
+
Sync version of {{domxref("IDBCursor")}}.
+
+ +

Examples

+ + + +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("IndexedDB 2")}}{{Spec2("IndexedDB 2")}}
{{SpecName('IndexedDB')}}{{Spec2('IndexedDB')}}Initial definition
+ +

See also

+ + diff --git a/files/he/web/api/storage/clear/index.html b/files/he/web/api/storage/clear/index.html new file mode 100644 index 0000000000..f93b7cf4a4 --- /dev/null +++ b/files/he/web/api/storage/clear/index.html @@ -0,0 +1,52 @@ +--- +title: Storage.clear() +slug: Web/API/Storage/clear +translation_of: Web/API/Storage/clear +--- +

{{APIRef("Web Storage API")}}

+ +

פונקציית ()clear מאפשרת לנקות את כל המפתחות מהאחסון המקומי.

+ +

תחביר

+ +
storage.clear();
+ +

ערך חוזר

+ +

undefined.

+ +

דוגמאות

+ +

הפונקציה הבאה יוצרת שלושה פריטים באחסון המקומי, ולאחר מכן מוחקת אותם.

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'red');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'miGato.png');
+
+  localStorage.clear();
+}
+
+ +

מפרט

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#dom-storage-clear', 'Storage.clear')}}{{Spec2('HTML WHATWG')}} 
+ +

תאימות דפדפן

+ + + +

{{Compat("api.Storage.clear")}}

diff --git a/files/he/web/api/storage/getitem/index.html b/files/he/web/api/storage/getitem/index.html new file mode 100644 index 0000000000..d18fcf9d3d --- /dev/null +++ b/files/he/web/api/storage/getitem/index.html @@ -0,0 +1,75 @@ +--- +title: localStorage.getItem() +slug: Web/API/Storage/getItem +translation_of: Web/API/Storage/getItem +--- +

{{APIRef("Web Storage API")}}

+ +

 

+ +

פונקציית ()getItem מאפשרת לאחזר נתונים מהאחסון המקומי באמצעות שם המפתח.
+ במידה והמפתח שרוצים לאחזר אינו קיים באחסון המקומי, יוחזר הערך null.

+ +

תחביר

+ +
var aValue = localStorage.getItem(keyName);
+
+ +

פרמטרים

+ +
+
keyName
+
שם המפתח אותו רוצים לאחזר.
+
+ +

ערך חוזר

+ +

במידה והמפתח קיים באחסון המקומי הוא יחזיר את ערכו. במידה והמפתח אינו קיים יוחזר הערך null.

+ +

דוגמאות

+ +

הפונקציה הבאה מאחזרת שלושה פריטי נתונים מהאחסון המקומי ולאחר מכן משתמשת בהם כדי להגדיר גיליונות סגנון מדורגים.

+ +
function setStyles() {
+  var currentColor = localStorage.getItem('bgcolor');
+  var currentFont = localStorage.getItem('font');
+  var currentImage = localStorage.getItem('image');
+
+  currentColor = document.getElementById('bgcolor').value;
+  currentFont = document.getElementById('font').value;
+  currentImage = document.getElementById('image').value;
+
+  htmlElem.style.backgroundColor = '#' + currentColor;
+  pElem.style.fontFamily = currentFont;
+  imgElem.setAttribute('src', currentImage);
+}
+ +

מפרט

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#dom-storage-getitem', 'Storage.getItem')}}{{Spec2('HTML WHATWG')}} 
+ +

תאימות דפדפן

+ + + +

{{Compat("api.Storage.getItem")}}

+ +

ראו גם

+ + diff --git a/files/he/web/api/storage/index.html b/files/he/web/api/storage/index.html new file mode 100644 index 0000000000..b89a1ef6a2 --- /dev/null +++ b/files/he/web/api/storage/index.html @@ -0,0 +1,107 @@ +--- +title: Storage +slug: Web/API/Storage +tags: + - API + - Interface + - NeedsTranslation + - Reference + - Storage + - TopicStub + - Web Storage + - data +translation_of: Web/API/Storage +--- +

{{APIRef("Web Storage API")}}

+ +

The Storage interface of the Web Storage API provides access to a particular domain's session or local storage. It allows, for example, the addition, modification, or deletion of stored data items.

+ +

To manipulate, for instance, the session storage for a domain, a call to the {{domxref("Window.sessionStorage")}} is made; whereas for local storage the call is made to {{domxref("Window.localStorage")}}.

+ +

Properties

+ +
+
{{domxref("Storage.length")}} {{readonlyInline}}
+
Returns an integer representing the number of data items stored in the Storage object.
+
+ +

Methods

+ +
+
{{domxref("Storage.key()")}}
+
When passed a number n, this method will return the name of the nth key in the storage.
+
+ +
+
{{domxref("Storage.getItem()")}}
+
When passed a key name, will return that key's value.
+
{{domxref("Storage.setItem()")}}
+
When passed a key name and value, will add that key to the storage, or update that key's value if it already exists.
+
{{domxref("Storage.removeItem()")}}
+
When passed a key name, will remove that key from the storage.
+
{{domxref("Storage.clear()")}}
+
When invoked, will empty all keys out of the storage.
+
+ +

Examples

+ +

Here we access a Storage object by calling localStorage. We first test whether the local storage contains data items using !localStorage.getItem('bgcolor'). If it does, we run a function called setStyles() that grabs the data items using {{domxref("Storage.getItem()")}} and uses those values to update page styles. If it doesn't, we run another function, populateStorage(), which uses {{domxref("Storage.setItem()")}} to set the item values, then runs setStyles().

+ +
if(!localStorage.getItem('bgcolor')) {
+  populateStorage();
+}
+setStyles();
+
+function populateStorage() {
+  localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);
+  localStorage.setItem('font', document.getElementById('font').value);
+  localStorage.setItem('image', document.getElementById('image').value);
+}
+
+function setStyles() {
+  var currentColor = localStorage.getItem('bgcolor');
+  var currentFont = localStorage.getItem('font');
+  var currentImage = localStorage.getItem('image');
+
+  document.getElementById('bgcolor').value = currentColor;
+  document.getElementById('font').value = currentFont;
+  document.getElementById('image').value = currentImage;
+
+  htmlElem.style.backgroundColor = '#' + currentColor;
+  pElem.style.fontFamily = currentFont;
+  imgElem.setAttribute('src', currentImage);
+}
+ +
+

Note: To see this running as a complete working example, see our Web Storage Demo.

+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#the-storage-interface', 'Storage')}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ + + +

{{Compat("api.Storage")}}

+ +

See also

+ + diff --git a/files/he/web/api/storage/key/index.html b/files/he/web/api/storage/key/index.html new file mode 100644 index 0000000000..9dfce0e52b --- /dev/null +++ b/files/he/web/api/storage/key/index.html @@ -0,0 +1,55 @@ +--- +title: Storage.key() +slug: Web/API/Storage/key +translation_of: Web/API/Storage/key +--- +

{{APIRef("Web Storage API")}}

+ +

פונקציית ()key מאפשרת לאחזר את שם המפתח באמצעות אינדקס.

+ +

תחביר

+ +
var aKeyName = storage.key(index);
+ +

פרמטרים

+ +
+
index
+
מספר שלם המייצג את מיקום המפתח שברצוננו לאחזר.
+
+ +

ערך חוזר

+ +

במידה והמפתח קיים באחסון המקומי הוא יחזיר את שמו. במידה והמפתח אינו קיים יוחזר הערך null.

+ +

דוגמאות

+ +

הפונקציה הבאה חוזרת על פריטי האחסון המקומיים ומקבלת את הערך שהוגדר עבור כל מפתח:

+ +
for(var i =0; i < localStorage.length; i++){
+   console.log(localStorage.getItem(localStorage.key(i)));
+}
+
+ +

מפרט

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#dom-storage-key', 'Storage.key')}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ + + +

{{Compat("api.Storage.key")}}

diff --git a/files/he/web/api/storage/length/index.html b/files/he/web/api/storage/length/index.html new file mode 100644 index 0000000000..6939e0bd1f --- /dev/null +++ b/files/he/web/api/storage/length/index.html @@ -0,0 +1,51 @@ +--- +title: Storage.length +slug: Web/API/Storage/length +translation_of: Web/API/Storage/length +--- +

{{APIRef("Web Storage API")}}

+ +

המאפיין length מאפשר לאחזר את מספר כל הפריטים שנמצאים באחסון המקומי ולהציגם באמצעות מספר שלם.

+ +

תחביר

+ +
var aLength = Storage.length;
+ +

ערך חוזר

+ +

מספר שלם.

+ +

דוגמאות

+ +

הפונקציה הבאה מוסיפה שלושה פריטים לאחסון המקומי ולאחר מכן מחזירה את מספר כל הפריטים שנמצאים באחסון המקומי:

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'yellow');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'cats.png');
+
+  localStorage.length; // should return 3
+}
+ +

מפרט

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#dom-storage-length', 'Storage.length')}}{{Spec2('HTML WHATWG')}} 
+ +

תאימות דפדפן

+ + + +

{{Compat("api.Storage.length")}}

diff --git a/files/he/web/api/storage/removeitem/index.html b/files/he/web/api/storage/removeitem/index.html new file mode 100644 index 0000000000..5760eae6b3 --- /dev/null +++ b/files/he/web/api/storage/removeitem/index.html @@ -0,0 +1,66 @@ +--- +title: Storage.removeItem() +slug: Web/API/Storage/removeItem +translation_of: Web/API/Storage/removeItem +--- +

{{APIRef("Web Storage API")}}

+ +

פונקציית ()removeItem מאפשרת לאחזר נתונים מהאחסון המקומי באמצעות שם המפתח.
+ ובמידה ושם המפתח לא קיים באחסון המקומי לא יבוצעו שינויים.

+ +

תחביר

+ +
storage.removeItem(keyName);
+ +

פרמטרים

+ +
+
keyName
+
שם המפתח אותו רוצים למחוק.
+
+ +

ערך חוזר

+ +

חלל ריק.

+ +

דוגמאות

+ +

הפונקציה הבאה יוצרת שלושה פריטים בתוך האחסון המקומי ולאחר מכן מסירה את פריט התמונה מהאחסון המקומי.

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'red');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'myCat.png');
+
+  localStorage.removeItem('image');
+}
+ +

מפרט

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#dom-storage-removeitem', 'Storage.removeItem')}}{{Spec2('HTML WHATWG')}} 
+ +

תאימות דפדפן

+ + + +

{{Compat("api.Storage.removeItem")}}

+ +

ראו גם

+ + diff --git a/files/he/web/api/storage/setitem/index.html b/files/he/web/api/storage/setitem/index.html new file mode 100644 index 0000000000..84225ee467 --- /dev/null +++ b/files/he/web/api/storage/setitem/index.html @@ -0,0 +1,69 @@ +--- +title: Storage.setItem() +slug: Web/API/Storage/setItem +translation_of: Web/API/Storage/setItem +--- +

{{APIRef("Web Storage API")}}
+ פונקציית ()setItem מאפשרת להוסיף נתונים אל האחסון המקומי באמצעות שני פרמטרים: שם מפתח וערך שאותם תיצור או תעדכן במידה וקיימים.

+ +

תחביר

+ +
storage.setItem(keyName, keyValue);
+ +

פרמטרים

+ +
+
keyName
+
מכיל את שמו של המפתח אותו יש ליצור או לעדכן.
+
keyValue
+
מכיל את שם הערך שיתווסף למפתח אותו אנו יוצרים או מעדכנים.
+
+ +

ערך חוזר

+ +

undefined.

+ +

החרגות

+ +

במידה והאחסון מלא המערכות עשויה לנקות נתונים מהאחסון המקומי.
+ בגרסה הניידת של דפדפן Safari, במידה והמשתמש נכנס אל מצב פרטי המערכת אינה שומרת נתונים באחסון המקומי ומסירה אותם באופן אוטומטי בשל מגבלת גודל של 0 בתים.

+ +

דוגמאות

+ +

הפונקציה הבאה יוצרת שלושה פריטי נתונים בתוך האחסון המקומי.

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'red');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'myCat.png');
+}
+ +

מפרט

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#dom-storage-setitem', 'Storage.setItem')}}{{Spec2('HTML WHATWG')}} 
+ +

תאימות דפדפן

+ + + +

{{Compat("api.Storage.setItem")}}

+ +

ראו גם

+ + diff --git a/files/he/web/api/web_storage_api/index.html b/files/he/web/api/web_storage_api/index.html new file mode 100644 index 0000000000..51a64e09b3 --- /dev/null +++ b/files/he/web/api/web_storage_api/index.html @@ -0,0 +1,111 @@ +--- +title: ממשק פיתוח היישומים Web Storage +slug: Web/API/Web_Storage_API +translation_of: Web/API/Web_Storage_API +--- +
{{DefaultAPISidebar("Web Storage API")}}
+ +

The Web Storage API provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using {{glossary("cookie", "cookies")}}.

+ +

Web Storage concepts and usage

+ +

The two mechanisms within Web Storage are as follows:

+ + + +

These mechanisms are available via the {{domxref("Window.sessionStorage")}} and {{domxref("Window.localStorage")}} properties (to be more precise, in supporting browsers the Window object implements the WindowLocalStorage and WindowSessionStorage objects, which the localStorage and sessionStorage properties hang off) — invoking one of these will create an instance of the {{domxref("Storage")}} object, through which data items can be set, retrieved and removed. A different Storage object is used for the sessionStorage and localStorage for each origin — they function and are controlled separately.

+ +
+

Note: From Firefox 45 onwards, when the browser crashes/restarts, the amount of data saved per origin is limited to 10MB. This has been done to avoid memory issues caused by excessive usage of web storage.

+
+ +
+

Note: Access to Web Storage from third-party IFrames is denied if the user has disabled third-party cookies (Firefox implements this behaviour from version 43 onwards.)

+
+ +
+

Note: Web Storage is not the same as mozStorage (Mozilla's XPCOM interfaces to SQLite) or the Session store API (an XPCOM storage utility for use by extensions).

+
+ +

Web Storage interfaces

+ +
+
{{domxref("Storage")}}
+
Allows you to set, retrieve and remove data for a specific domain and storage type (session or local.)
+
{{domxref("Window")}}
+
The Web Storage API extends the {{domxref("Window")}} object with two new properties — {{domxref("Window.sessionStorage")}} and {{domxref("Window.localStorage")}} — which provide access to the current domain's session and local {{domxref("Storage")}} objects respectively, and a {{domxref("Window.onstorage")}} event handler that fires when a storage area changes (e.g. a new item is stored.)
+
{{domxref("StorageEvent")}}
+
The storage event is fired on a document's Window object when a storage area changes.
+
+ +

Examples

+ +

To illustrate some typical web storage usage, we have created a simple example, imaginatively called Web Storage Demo. The landing page provides controls that can be used to customize the colour, font and decorative image. When you choose different options, the page is instantly updated; in addition your choices are stored in localStorage, so that when you leave the page then load it again later on your choices are remembered.

+ +

In addition, we have provided an event output page — if you load this page in another tab, then make changes to your choices in the landing page, you'll see the updated storage information outputted as the {{domxref("StorageEvent")}} is fired.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#webstorage')}}{{Spec2('HTML WHATWG')}}
+ +

Browser compatibility

+ +

Window.localStorage

+ +
+ + +

{{Compat("api.Window.localStorage")}}

+ +

Window.sessionStorage

+ +
+ + +

{{Compat("api.Window.sessionStorage")}}

+
+
+ +

Private Browsing / Incognito modes

+ +

Most modern browsers support a privacy option called 'Incognito', 'Private Browsing' or something similar that doesn't store data like history and cookies. This is fundamentally incompatible with Web Storage for obvious reasons. As such, browser vendors are experimenting with different scenarios for how to deal with this incompatibility.

+ +

Most browsers have opted for a strategy where storage APIs are still available and seemingly fully functional, with the one big difference that all stored data is wiped after the browser is closed. For these browsers there are still different interpretations of what should be done with existing stored data (from a regular browsing session). Should it be available to read when in Private mode? Then there are some browsers, most notably Safari, that have opted for a solution where storage is available, but is empty and has a quota of 0 bytes assigned, effectively making it impossible to write data to it.

+ +

Developers should be aware of these different implementations and take them into account when developing websites depending on Web Storage APIs. For more information please have a look at this WHATWG blog post that specifically deals with this topic.

+ +

See also

+ + diff --git a/files/he/web/api/window/alert/index.html b/files/he/web/api/window/alert/index.html new file mode 100644 index 0000000000..0346b5f73a --- /dev/null +++ b/files/he/web/api/window/alert/index.html @@ -0,0 +1,70 @@ +--- +title: Window.alert() +slug: Web/API/Window/alert +tags: + - אזהרה + - חלון הודעה + - פופ-אפ +translation_of: Web/API/Window/alert +--- +

{{ APIRef }}

+ +

Window.alert() - מציגה הודעת אזהרה עם תוכן וכפתור לאישור וסגירה.

+ +

תחביר

+ +
window.alert(message);
+ +

פרמטרים

+ +
+
message {{optional_inline}}
+
מחרוזת שתופיעה כגוף ההודעה בתיבת הדו-שיח של ההתראה.
+
+ +

דוגמאות

+ +
window.alert("Hello world!");
+alert("Hello world!");
+ +

שתי הדוגמאות מייצרות את ההודעה הבאה:

+ +

Image:AlertHelloWorld.png

+ +

הערות

+ +

 

+ +

תפקידן של תיבות ההתראה הינן להצגת הודעות שאינן דורשות תגובה מצד המשתמש, מלבד היכרות וקריאת ההודעה.

+ +

 

+ +

מפרט

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'timers-and-user-prompts.html#dom-alert', 'alert()')}}{{Spec2('HTML WHATWG')}} 
+ +

תאימות דפדפן

+ + + +

{{Compat("api.Window.alert")}}

+ +

ראה גם

+ + diff --git a/files/he/web/api/window/confirm/index.html b/files/he/web/api/window/confirm/index.html new file mode 100644 index 0000000000..54ab3e903a --- /dev/null +++ b/files/he/web/api/window/confirm/index.html @@ -0,0 +1,70 @@ +--- +title: Window.confirm() +slug: Web/API/Window/confirm +tags: + - אישור הודעה + - דפדפן + - הודעה + - חלון התראה + - פופ-אפ +translation_of: Web/API/Window/confirm +--- +
{{ApiRef("Window")}}
+ +
Window.confirm() - מציגה תיבת דו-שיח עם תוכן וכפתורי אישור וביטול.
+ +

תחביר

+ +
result = window.confirm(message);
+
+ + + +

דוגמאות

+ +
if (window.confirm("Do you really want to leave?")) {
+  window.open("exit.html", "Thanks for Visiting!");
+}
+
+ +

הדוגמה תציג את ההודעה הבאה:

+ +

firefox confirm
+  

+ +

הערות

+ +

The following text is shared between this article, DOM:window.prompt and DOM:window.alert תיבות דו-שיח מונעות מהמשתמש גישה לממשק התוכנית עד אשר היא תיסגר.

+ +

מפרט

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'timers-and-user-prompts.html#dom-confirm', 'confirm()')}}{{Spec2('HTML WHATWG')}} 
+ +

תאימות דפדפן

+ + + +

{{Compat("api.Window.confirm")}}

+ +

ראה גם

+ + diff --git a/files/he/web/api/window/index.html b/files/he/web/api/window/index.html new file mode 100644 index 0000000000..70b807464b --- /dev/null +++ b/files/he/web/api/window/index.html @@ -0,0 +1,509 @@ +--- +title: Window +slug: Web/API/Window +tags: + - API + - DOM + - Interface + - JavaScript + - NeedsTranslation + - Reference + - Tab + - TopicStub + - Window +translation_of: Web/API/Window +--- +
{{APIRef("DOM")}}
+ +

The Window interface represents a window containing a DOM document; the document property points to the DOM document loaded in that window. A window for a given document can be obtained using the {{domxref("document.defaultView")}} property.

+ +

A global variable, window, representing the window in which the script is running, is exposed to JavaScript code.

+ +

The Window interface is home to a variety of functions, namespaces, objects, and constructors which are not necessarily directly associated with the concept of a user interface window. However, the Window interface is a suitable place to include these items that need to be globally available. Many of these are documented in the  JavaScript Reference and the DOM Reference.

+ +

In a tabbed browser, each tab is represented by its own Window object; the global window seen by JavaScript code running within a given tab always represents the tab in which the code is running. That said, even in a tabbed browser, some properties and methods still apply to the overall window that contains the tab, such as {{Domxref("Window.resizeTo", "resizeTo()")}} and {{Domxref("Window.innerHeight", "innerHeight")}}. Generally, anything that can't reasonably pertain to a tab pertains to the window instead.

+ +

{{InheritanceDiagram}}

+ +

Properties

+ +

This interface inherits properties from the {{domxref("EventTarget")}} interface and implements properties from the {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("WindowEventHandlers")}} mixins.

+ +

Note that properties which are objects (e.g.,. for overriding the prototype of built-in elements) are listed in a separate section below.

+ +
+
{{domxref("Window.closed")}} {{Non-standard_inline}} {{readOnlyInline}}
+
This property indicates whether the current window is closed or not.
+
{{domxref("Window.console")}} {{ReadOnlyInline}}
+
Returns a reference to the console object which provides access to the browser's debugging console.
+
{{domxref("Window.content")}} and Window._content {{Non-standard_inline}} {{obsolete_inline}} {{ReadOnlyInline}}
+
Returns a reference to the content element in the current window. Since Firefox 57 (initially Nightly-only), both versions are only available from chrome (privileged) code, and not available to the web anymore.
+
{{domxref("Window.controllers")}} {{non-standard_inline}} {{ReadOnlyInline}}
+
Returns the XUL controller objects for the current chrome window.
+
{{domxref("Window.customElements")}} {{ReadOnlyInline}}
+
returns a reference to the {{domxref("CustomElementRegistry")}} object, which can be used to register new custom elements and get information about previously registered custom elements.
+
{{domxref("Window.crypto")}} {{readOnlyInline}}
+
Returns the browser crypto object.
+
{{domxref("Window.defaultStatus")}} {{Obsolete_inline("gecko23")}}
+
Gets/sets the status bar text for the given window.
+
{{domxref("Window.devicePixelRatio")}} {{non-standard_inline}} {{ReadOnlyInline}}
+
Returns the ratio between physical pixels and device independent pixels in the current display.
+
{{domxref("Window.dialogArguments")}} {{Fx_minversion_inline(3)}} {{ReadOnlyInline}}
+
Gets the arguments passed to the window (if it's a dialog box) at the time {{domxref("window.showModalDialog()")}} was called. This is an {{Interface("nsIArray")}}.
+
{{domxref("Window.directories")}} {{obsolete_inline}}
+
Synonym of {{domxref("window.personalbar")}}
+
{{domxref("Window.document")}} {{ReadOnlyInline}}
+
Returns a reference to the document that the window contains.
+
{{domxref("Window.DOMMatrix")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMMatrix")}} object, which represents 4x4 matrices, suitable for 2D and 3D operations.
+
{{domxref("Window.DOMMatrixReadOnly")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMMatrixReadOnly")}} object, which represents 4x4 matrices, suitable for 2D and 3D operations.
+
{{domxref("Window.DOMPoint")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMPoint")}} object, which represents a 2D or 3D point in a coordinate system.
+
{{domxref("Window.DOMPointReadOnly")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMPointReadOnly")}} object, which represents a 2D or 3D point in a coordinate system.
+
{{domxref("Window.DOMQuad")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMQuad")}} object, which provides represents a quadrilaterial object, that is one having four corners and four sides.
+
{{domxref("Window.DOMRect")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMRect")}} object, which represents a rectangle.
+
{{domxref("Window.DOMRectReadOnly")}} {{readOnlyInline}} {{experimental_inline}}
+
Returns a reference to a {{domxref("DOMRectReadOnly")}} object, which represents a rectangle.
+
{{domxref("Window.event")}} {{ReadOnlyInline}}
+
Returns the current event, which is the event currently being handled by the JavaScript code's context, or undefined if no event is currently being handled. The {{domxref("Event")}} object passed directly to event handlers should be used instead whenever possible.
+
{{domxref("Window.frameElement")}} {{readOnlyInline}}
+
Returns the element in which the window is embedded, or null if the window is not embedded.
+
{{domxref("Window.frames")}} {{readOnlyInline}}
+
Returns an array of the subframes in the current window.
+
{{domxref("Window.fullScreen")}} {{gecko_minversion_inline("1.9")}}
+
This property indicates whether the window is displayed in full screen or not.
+
{{domxref("Window.globalStorage")}} {{gecko_minversion_inline("1.8.1")}} {{Non-standard_inline}} {{Obsolete_inline("gecko13")}}
+
Unsupported since Gecko 13 (Firefox 13). Use {{domxref("Window.localStorage")}} instead.
+ Was: Multiple storage objects that are used for storing data across multiple pages.
+
{{domxref("Window.history")}} {{ReadOnlyInline}}
+
Returns a reference to the history object.
+
{{domxref("Window.innerHeight")}} {{readOnlyInline}}
+
Gets the height of the content area of the browser window including, if rendered, the horizontal scrollbar.
+
{{domxref("Window.innerWidth")}} {{readOnlyInline}}
+
Gets the width of the content area of the browser window including, if rendered, the vertical scrollbar.
+
{{domxref("Window.isSecureContext")}} {{experimental_inline}} {{readOnlyInline}}
+
Indicates whether a context is capable of using features that require secure contexts.
+
{{domxref("Window.length")}} {{readOnlyInline}}
+
Returns the number of frames in the window. See also {{domxref("window.frames")}}.
+
{{domxref("Window.location")}}
+
Gets/sets the location, or current URL, of the window object.
+
{{domxref("Window.locationbar")}} {{ReadOnlyInline}}
+
Returns the locationbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.localStorage")}} {{readOnlyInline}} {{gecko_minversion_inline("1.9.1")}}
+
Returns a reference to the local storage object used to store data that may only be accessed by the origin that created it.
+
{{domxref("Window.menubar")}} {{ReadOnlyInline}}
+
Returns the menubar object, whose visibility can be toggled in the window.
+
{{domxref("Window.messageManager")}} {{gecko_minversion_inline("2.0")}}
+
Returns the message manager object for this window.
+
{{domxref("Window.mozAnimationStartTime")}} {{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}} {{Deprecated_inline}}
+
The time in milliseconds since epoch at which the current animation cycle began. Use {{domxref("Animation.startTime")}} instead.
+
{{domxref("Window.mozInnerScreenX")}} {{ReadOnlyInline}} {{non-standard_inline}} {{gecko_minversion_inline("1.9.2")}}
+
Returns the horizontal (X) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel in {{interface("nsIDOMWindowUtils")}} for a conversion factor to adapt to screen pixels if needed.
+
{{domxref("Window.mozInnerScreenY")}} {{ReadOnlyInline}} {{non-standard_inline}} {{gecko_minversion_inline("1.9.2")}}
+
Returns the vertical (Y) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel for a conversion factor to adapt to screen pixels if needed.
+
{{domxref("Window.mozPaintCount")}} {{non-standard_inline}} {{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}}
+
Returns the number of times the current document has been rendered to the screen in this window. This can be used to compute rendering performance.
+
{{domxref("Window.name")}}
+
Gets/sets the name of the window.
+
{{domxref("Window.navigator")}} {{readOnlyInline}}
+
Returns a reference to the navigator object.
+
{{domxref("Window.opener")}}
+
Returns a reference to the window that opened this current window.
+
{{domxref("Window.orientation")}} {{non-standard_inline}} {{deprecated_inline}} {{readOnlyInline}}
+
Returns the orientation in degrees (in 90 degree increments) of the viewport relative to the device's natural orientation.
+
{{domxref("Window.outerHeight")}} {{readOnlyInline}}
+
Gets the height of the outside of the browser window.
+
{{domxref("Window.outerWidth")}} {{readOnlyInline}}
+
Gets the width of the outside of the browser window.
+
{{domxref("Window.scrollX","Window.pageXOffset")}} {{readOnlyInline}}
+
An alias for {{domxref("window.scrollX")}}.
+
{{domxref("Window.scrollY","Window.pageYOffset")}} {{readOnlyInline}}
+
An alias for {{domxref("window.scrollY")}}
+
{{domxref("Window.parent")}} {{readOnlyInline}}
+
Returns a reference to the parent of the current window or subframe.
+
{{domxref("Window.performance")}} {{readOnlyInline}}
+
Returns a {{domxref("Performance")}} object, which includes the {{domxref("Performance.timing", "timing")}} and {{domxref("Performance.navigation", "navigation")}} attributes, each of which is an object providing performance-related data. See also Using Navigation Timing for additional information and examples.
+
{{domxref("Window.personalbar")}} {{readOnlyInline}}
+
Returns the personalbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.pkcs11")}} {{obsolete_inline(29)}}
+
Formerly provided access to install and remove PKCS11 modules.
+
{{domxref("Window.returnValue")}} {{Fx_minversion_inline(3)}}
+
The return value to be returned to the function that called {{domxref("window.showModalDialog()")}} to display the window as a modal dialog.
+
{{domxref("Window.screen")}} {{readOnlyInline}}
+
Returns a reference to the screen object associated with the window.
+ +
{{domxref("Window.screenX")}} {{readOnlyInline}}
+
Returns the horizontal distance of the left border of the user's browser from the left side of the screen.
+
{{domxref("Window.screenY")}} {{readOnlyInline}}
+
Returns the vertical distance of the top border of the user's browser from the top side of the screen.
+
{{domxref("Window.scrollbars")}} {{readOnlyInline}}
+
Returns the scrollbars object, whose visibility can be toggled in the window.
+
{{domxref("Window.scrollMaxX")}} {{non-standard_inline}} {{ReadOnlyInline}}
+
The maximum offset that the window can be scrolled to horizontally, that is the document width minus the viewport width.
+
{{domxref("Window.scrollMaxY")}} {{non-standard_inline}} {{ReadOnlyInline}}
+
The maximum offset that the window can be scrolled to vertically (i.e., the document height minus the viewport height).
+
{{domxref("Window.scrollX")}} {{readOnlyInline}}
+
Returns the number of pixels that the document has already been scrolled horizontally.
+
{{domxref("Window.scrollY")}} {{readOnlyInline}}
+
Returns the number of pixels that the document has already been scrolled vertically.
+
{{domxref("Window.self")}} {{ReadOnlyInline}}
+
Returns an object reference to the window object itself.
+
{{domxref("Window.sessionStorage")}}
+
Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it.
+
{{domxref("Window.sidebar")}} {{non-standard_inline}} {{ReadOnlyInline}}
+
Returns a reference to the window object of the sidebar.
+
{{domxref("Window.speechSynthesis")}} {{ReadOnlyInline}}
+
Returns a {{domxref("SpeechSynthesis")}} object, which is the entry point into using Web Speech API speech synthesis functionality.
+
{{domxref("Window.status")}}
+
Gets/sets the text in the statusbar at the bottom of the browser.
+
{{domxref("Window.statusbar")}} {{readOnlyInline}}
+
Returns the statusbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.toolbar")}} {{readOnlyInline}}
+
Returns the toolbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.top")}} {{readOnlyInline}}
+
Returns a reference to the topmost window in the window hierarchy. This property is read only.
+
{{domxref("Window.visualViewport")}} {{readOnlyInline}}
+
Returns a {{domxref("VisualViewport")}} object which represents the visual viewport for a given window.
+
{{domxref("Window.window")}} {{ReadOnlyInline}}
+
Returns a reference to the current window.
+
window[0], window[1], etc.
+
Returns a reference to the window object in the frames. See {{domxref("Window.frames")}} for more details.
+
+ +

Properties implemented from elsewhere

+ +
+
{{domxref("WindowOrWorkerGlobalScope.caches")}} {{readOnlyinline}}
+
Returns the {{domxref("CacheStorage")}} object associated with the current context. This object enables functionality such as storing assets for offline use, and generating custom responses to requests.
+
{{domxref("WindowOrWorkerGlobalScope.indexedDB")}} {{readonlyInline}}
+
Provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an {{domxref("IDBFactory")}} object.
+
{{domxref("WindowOrWorkerGlobalScope.isSecureContext")}} {{readOnlyinline}}
+
Returns a boolean indicating whether the current context is secure (true) or not (false).
+
{{domxref("WindowOrWorkerGlobalScope.origin")}} {{readOnlyinline}}
+
Returns the global object's origin, serialized as a string. (This does not yet appear to be implemented in any browser.)
+
+ +

Methods

+ +

This interface inherits methods from the {{domxref("EventTarget")}} interface and implements methods from {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("EventTarget")}}.

+ +
+
{{domxref("Window.alert()")}}
+
Displays an alert dialog.
+ +
{{domxref("Window.back()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Moves back one in the window history. This method is obsolete; you should instead use {{domxref("History.back", "window.history.back()")}}.
+
{{domxref("Window.blur()")}}
+
Sets focus away from the window.
+
{{domxref("Window.cancelAnimationFrame()")}} {{experimental_inline}}
+
Enables you to cancel a callback previously scheduled with {{domxref("Window.requestAnimationFrame")}}.
+
{{domxref("Window.cancelIdleCallback()")}} {{experimental_inline}}
+
Enables you to cancel a callback previously scheduled with {{domxref("Window.requestIdleCallback")}}.
+
{{domxref("Window.captureEvents()")}} {{Deprecated_inline}}
+
Registers the window to capture all events of the specified type.
+
{{domxref("Window.clearImmediate()")}}
+
Cancels the repeated execution set using setImmediate.
+
{{domxref("Window.close()")}}
+
Closes the current window.
+
{{domxref("Window.confirm()")}}
+
Displays a dialog with a message that the user needs to respond to.
+
{{domxref("Window.disableExternalCapture()")}} {{obsolete_inline(24)}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.dispatchEvent()")}}
+
Used to trigger an event.
+
{{domxref("Window.dump()")}} {{Non-standard_inline}}
+
Writes a message to the console.
+
{{domxref("Window.enableExternalCapture()")}} {{obsolete_inline(24)}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.find()")}}
+
Searches for a given string in a window.
+
{{domxref("Window.focus()")}}
+
Sets focus on the current window.
+
{{domxref("Window.forward()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Moves the window one document forward in the history. This method is obsolete; you should instead use {{domxref("History.forward", "window.history.forward()")}}.
+
{{domxref("Window.getAttention()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Flashes the application icon.
+
{{domxref("Window.getAttentionWithCycleCount()")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.getComputedStyle()")}}
+
Gets computed style for the specified element. Computed style indicates the computed values of all CSS properties of the element.
+
{{domxref("Window.getDefaultComputedStyle()")}} {{Non-standard_inline}}
+
Gets default computed style for the specified element, ignoring author stylesheets.
+
{{domxref("Window.getSelection()")}}
+
Returns the selection object representing the selected item(s).
+
{{domxref("Window.home()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Returns the browser to the home page.
+
{{domxref("Window.matchMedia()")}} {{gecko_minversion_inline("6.0")}}
+
Returns a {{domxref("MediaQueryList")}} object representing the specified media query string.
+
{{domxref("Window.maximize()")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.minimize()")}} (top-level XUL windows only)
+
Minimizes the window.
+
{{domxref("Window.moveBy()")}}
+
Moves the current window by a specified amount.
+
{{domxref("Window.moveTo()")}}
+
Moves the window to the specified coordinates.
+
{{domxref("Window.open()")}}
+
Opens a new window.
+
{{domxref("Window.openDialog()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Opens a new dialog window.
+
{{domxref("Window.postMessage()")}} {{Fx_minversion_inline(3)}}
+
Provides a secure means for one window to send a string of data to another window, which need not be within the same domain as the first.
+
{{domxref("Window.print()")}}
+
Opens the Print Dialog to print the current document.
+
{{domxref("Window.prompt()")}}
+
Returns the text entered by the user in a prompt dialog.
+
{{domxref("Window.releaseEvents()")}} {{Non-standard_inline}} {{Deprecated_inline}}
+
Releases the window from trapping events of a specific type.
+
{{domxref("Window.requestAnimationFrame()")}} {{gecko_minversion_inline("2.0")}}
+
Tells the browser that an animation is in progress, requesting that the browser schedule a repaint of the window for the next animation frame.
+
{{domxref("Window.requestIdleCallback()")}}  {{experimental_inline}}
+
Enables the scheduling of tasks during a browser's idle periods.
+
{{domxref("Window.resizeBy()")}}
+
Resizes the current window by a certain amount.
+
{{domxref("Window.resizeTo()")}}
+
Dynamically resizes window.
+
{{domxref("Window.restore()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.routeEvent()")}} {{obsolete_inline(24)}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.scroll()")}}
+
Scrolls the window to a particular place in the document.
+
{{domxref("Window.scrollBy()")}}
+
Scrolls the document in the window by the given amount.
+
{{domxref("Window.scrollByLines()")}} {{Non-standard_inline}}
+
Scrolls the document by the given number of lines.
+
{{domxref("Window.scrollByPages()")}} {{Non-standard_inline}}
+
Scrolls the current document by the specified number of pages.
+
{{domxref("Window.scrollTo()")}}
+
Scrolls to a particular set of coordinates in the document.
+
{{domxref("Window.setCursor()")}} {{Non-standard_inline}} (top-level XUL windows only)
+
Changes the cursor for the current window
+
{{domxref("Window.setImmediate()")}}
+
Executes a function after the browser has finished other heavy tasks
+
{{domxref("Window.setResizable()")}} {{Non-standard_inline}}
+
Toggles a user's ability to resize a window.
+
{{domxref("Window.sizeToContent()")}} {{Non-standard_inline}}
+
Sizes the window according to its content.
+
{{domxref("Window.stop()")}}
+
This method stops window loading.
+
{{domxref("Window.updateCommands()")}} {{Non-standard_inline}}
+
Updates the state of commands of the current chrome window (UI).
+
+ +

Methods implemented from elsewhere

+ +
+
{{domxref("EventTarget.addEventListener()")}}
+
Register an event handler to a specific event type on the window.
+
{{domxref("WindowOrWorkerGlobalScope.atob()")}}
+
Decodes a string of data which has been encoded using base-64 encoding.
+
{{domxref("WindowOrWorkerGlobalScope.btoa()")}}
+
Creates a base-64 encoded ASCII string from a string of binary data.
+
{{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}
+
Cancels the repeated execution set using {{domxref("WindowOrWorkerGlobalScope.setInterval()")}}.
+
{{domxref("WindowOrWorkerGlobalScope.clearTimeout()")}}
+
Cancels the delayed execution set using {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.
+
{{domxref("WindowOrWorkerGlobalScope.createImageBitmap()")}}
+
Accepts a variety of different image sources, and returns a {{domxref("Promise")}} which resolves to an {{domxref("ImageBitmap")}}. Optionally the source is cropped to the rectangle of pixels originating at (sx, sy) with width sw, and height sh.
+
{{domxref("WindowOrWorkerGlobalScope.fetch()")}}
+
Starts the process of fetching a resource from the network.
+
{{domxref("EventTarget.removeEventListener")}}
+
Removes an event listener from the window.
+
{{domxref("WindowOrWorkerGlobalScope.setInterval()")}}
+
Schedules a function to execute every time a given number of milliseconds elapses.
+
{{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}
+
Schedules a function to execute in a given amount of time.
+
+ +

Obsolete methods

+ +
+
{{domxref("Window.showModalDialog()")}} {{obsolete_inline}}
+
Displays a modal dialog. This method was removed completely in Chrome 43, and Firefox 55.
+
+ +

Event handlers

+ +

These are properties of the window object that can be set to establish event handlers for the various things that can happen in the window that might be of interest.

+ +

This interface inherits event handlers from the {{domxref("EventTarget")}} interface and implements event handlers from {{domxref("WindowEventHandlers")}}.

+ +
+

Note: Starting in {{Gecko("9.0")}}, you can now use the syntax if ("onabort" in window) to determine whether or not a given event handler property exists. This is because event handler interfaces have been updated to be proper web IDL interfaces. See DOM event handlers for details.

+
+ +
+
{{domxref("Window.onappinstalled")}}
+
Called when the page is installed as a webapp. See {{event('appinstalled')}} event.
+
{{domxref("Window.onbeforeinstallprompt")}}
+
An event handler property dispatched before a user is prompted to save a web site to a home screen on mobile.
+
{{domxref("Window.ondevicelight")}}
+
An event handler property for any ambient light levels changes
+
{{domxref("Window.ondevicemotion")}} {{gecko_minversion_inline("6.0")}}
+
Called if accelerometer detects a change (For mobile devices)
+
{{domxref("Window.ondeviceorientation")}} {{gecko_minversion_inline("6.0")}}
+
Called when the orientation is changed (For mobile devices)
+
{{domxref("Window.ondeviceorientationabsolute")}} {{non-standard_inline}} Chrome only
+
An event handler property for any device orientation changes.
+
{{domxref("Window.ondeviceproximity")}}
+
An event handler property for device proximity event
+
{{domxref("Window.ongamepadconnected")}}
+
Represents an event handler that will run when a gamepad is connected (when the {{event('gamepadconnected')}} event fires).
+
{{domxref("Window.ongamepaddisconnected")}}
+
Represents an event handler that will run when a gamepad is disconnected (when the {{event('gamepaddisconnected')}} event fires).
+
{{domxref("Window.onmozbeforepaint")}} {{gecko_minversion_inline("2.0")}}
+
An event handler property for the MozBeforePaint event, which is sent before repainting the window if the event has been requested by a call to the {{domxref("Window.mozRequestAnimationFrame()")}} method.
+
{{domxref("Window.onpaint")}}
+
An event handler property for paint events on the window.
+
{{domxref("Window.onrejectionhandled")}} {{experimental_inline}}
+
An event handler for handled {{jsxref("Promise")}} rejection events.
+
{{domxref("Window.onuserproximity")}}
+
An event handler property for user proximity events.
+
{{domxref("Window.onvrdisplayconnect")}}
+
Represents an event handler that will run when a compatible VR device has been connected to the computer (when the {{event("vrdisplayconnected")}} event fires).
+
{{domxref("Window.onvrdisplaydisconnect")}}
+
Represents an event handler that will run when a compatible VR device has been disconnected from the computer (when the {{event("vrdisplaydisconnected")}} event fires).
+
{{domxref("Window.onvrdisplayactivate")}}
+
Represents an event handler that will run when a display is able to be presented to (when the {{event("vrdisplayactivate")}} event fires), for example if an HMD has been moved to bring it out of standby, or woken up by being put on.
+
{{domxref("Window.onvrdisplaydeactivate")}}
+
Represents an event handler that will run when a display can no longer be presented to (when the {{event("vrdisplaydeactivate")}} event fires), for example if an HMD has gone into standby or sleep mode due to a period of inactivity.
+
{{domxref("Window.onvrdisplayblur")}}
+
Represents an event handler that will run when presentation to a display has been paused for some reason by the browser, OS, or VR hardware (when the {{event("vrdisplayblur")}} event fires) — for example, while the user is interacting with a system menu or browser, to prevent tracking or loss of experience.
+
{{domxref("Window.onvrdisplayfocus")}}
+
Represents an event handler that will run when presentation to a display has resumed after being blurred (when the {{event("vrdisplayfocus")}} event fires).
+
{{domxref("Window.onvrdisplaypresentchange")}}
+
represents an event handler that will run when the presenting state of a VR device changes — i.e. goes from presenting to not presenting, or vice versa (when the {{event("vrdisplaypresentchange")}} event fires).
+
+ +

Event handlers implemented from elsewhere

+ +
+
{{domxref("GlobalEventHandlers.onabort")}}
+
Called when the loading of a resource has been aborted, such as by a user canceling the load while it is still in progress
+
{{domxref("WindowEventHandlers.onafterprint")}}
+
Called when the print dialog box is closed. See {{event("afterprint")}} event.
+
{{domxref("WindowEventHandlers.onbeforeprint")}}
+
Called when the print dialog box is opened. See {{event("beforeprint")}} event.
+
{{domxref("WindowEventHandlers.onbeforeunload")}}
+
An event handler property for before-unload events on the window.
+
{{domxref("GlobalEventHandlers.onblur")}}
+
Called after the window loses focus, such as due to a popup.
+
{{domxref("GlobalEventHandlers.onchange")}}
+
An event handler property for change events on the window.
+
{{domxref("GlobalEventHandlers.onclick")}}
+
Called after the ANY mouse button is pressed & released
+
{{domxref("GlobalEventHandlers.ondblclick")}}
+
Called when a double click is made with ANY mouse button.
+
{{domxref("GlobalEventHandlers.onclose")}}
+
Called after the window is closed
+
{{domxref("GlobalEventHandlers.oncontextmenu")}}
+
Called when the RIGHT mouse button is pressed
+
{{domxref("GlobalEventHandlers.onerror")}}
+
Called when a resource fails to load OR when an error occurs at runtime. See {{event("error")}} event.
+
{{domxref("GlobalEventHandlers.onfocus")}}
+
Called after the window receives or regains focus. See {{event("focus")}} events.
+
{{domxref("WindowEventHandlers.onhashchange")}} {{gecko_minversion_inline("1.9.2")}}
+
An event handler property for {{event('hashchange')}} events on the window; called when the part of the URL after the hash mark ("#") changes.
+
{{domxref("GlobalEventHandlers.oninput")}}
+
Called when the value of an <input> element changes
+
{{domxref("GlobalEventHandlers.onkeydown")}}
+
Called when you begin pressing ANY key. See {{event("keydown")}} event.
+
{{domxref("GlobalEventHandlers.onkeypress")}}
+
Called when a key (except Shift, Fn, and CapsLock) is in pressed position. See {{event("keypress")}} event.
+
{{domxref("GlobalEventHandlers.onkeyup")}}
+
Called when you finish releasing ANY key. See {{event("keyup")}} event.
+
{{domxref("WindowEventHandlers.onlanguagechange")}}
+
An event handler property for {{event("languagechange")}} events on the window.
+
{{domxref("GlobalEventHandlers.onload")}}
+
Called after all resources and the DOM are fully loaded. WILL NOT get called when the page is loaded from cache, such as with back button.
+
{{domxref("WindowEventHandlers.onmessage")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("message")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousedown")}}
+
Called when ANY mouse button is pressed.
+
{{domxref("GlobalEventHandlers.onmousemove")}}
+
Called continously when the mouse is moved inside the window.
+
{{domxref("GlobalEventHandlers.onmouseout")}}
+
Called when the pointer leaves the window.
+
{{domxref("GlobalEventHandlers.onmouseover")}}
+
Called when the pointer enters the window
+
{{domxref("GlobalEventHandlers.onmouseup")}}
+
Called when ANY mouse button is released
+
{{domxref("WindowEventHandlers.onoffline")}}
+
Called when network connection is lost. See {{event("offline")}} event.
+
{{domxref("WindowEventHandlers.ononline")}}
+
Called when network connection is established. See {{event("online")}} event.
+
{{domxref("WindowEventHandlers.onpagehide")}}
+
Called when the user navigates away from the page, before the onunload event. See {{event("pagehide")}} event.
+
{{domxref("WindowEventHandlers.onpageshow")}}
+
Called after all resources and the DOM are fully loaded. See {{event("pageshow")}} event.
+
{{domxref("WindowEventHandlers.onpopstate")}} {{gecko_minversion_inline("2.0")}}
+
Called when a back button is pressed.
+
{{domxref("GlobalEventHandlers.onreset")}}
+
Called when a form is reset
+
{{domxref("GlobalEventHandlers.onresize")}}
+
Called continuously as you are resizing the window.
+
{{domxref("GlobalEventHandlers.onscroll")}}
+
Called when the scroll bar is moved via ANY means. If the resource fully fits in the window, then this event cannot be invoked
+
{{domxref("GlobalEventHandlers.onwheel")}}
+
Called when the mouse wheel is rotated around any axis
+
{{domxref("GlobalEventHandlers.onselect")}}
+
Called after text in an input field is selected
+
{{domxref("GlobalEventHandlers.onselectionchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.
+
{{domxref("WindowEventHandlers.onstorage")}}
+
Called when there is a change in session storage or local storage. See {{event("storage")}} event
+
{{domxref("GlobalEventHandlers.onsubmit")}}
+
Called when a form is submitted
+
{{domxref("WindowEventHandlers.onunhandledrejection")}} {{experimental_inline}}
+
An event handler for unhandled {{jsxref("Promise")}} rejection events.
+
{{domxref("WindowEventHandlers.onunload")}}
+
Called when the user navigates away from the page.
+
+ +

Constructors

+ +

See also the DOM Interfaces.

+ +
+
{{domxref("DOMParser")}}
+
DOMParser can parse XML or HTML source stored in a string into a DOM DocumentDOMParser is specified in DOM Parsing and Serialization.
+
{{domxref("Window.GeckoActiveXObject")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Image")}}
+
Used for creating an {{domxref("HTMLImageElement")}}.
+
{{domxref("Option")}}
+
Used for creating an {{domxref("HTMLOptionElement")}}
+
{{domxref("Window.QueryInterface")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.StaticRange")}} {{experimental_inline}} {{readonlyinline}}
+
Returns a {{domxref('StaticRange.StaticRange','StaticRange()')}} constructor which creates a {{domxref('StaticRange')}} object.
+
{{domxref("Worker")}}
+
Used for creating a Web worker
+
{{domxref("Window.XMLSerializer")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.XPCNativeWrapper")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.XPCSafeJSObjectWrapper")}}
+
{{todo("NeedsContents")}}
+
+ +

Interfaces

+ +

See DOM Reference

+ +

Browser compatibility

+ + + +

{{Compat("api.Window")}}

+ +

See also

+ + diff --git a/files/he/web/api/window/localstorage/index.html b/files/he/web/api/window/localstorage/index.html new file mode 100644 index 0000000000..1f423a8ef1 --- /dev/null +++ b/files/he/web/api/window/localstorage/index.html @@ -0,0 +1,82 @@ +--- +title: Window.localStorage +slug: Web/API/Window/localStorage +translation_of: Web/API/Window/localStorage +--- +

{{APIRef("Web Storage API")}}

+ +

התכונה לקריאה בלבד  localStorage  מאפשרת לך לגשת לאובייקט מסוג {{DOMxRef("Storage")}} עבור המקור של   {{DOMxRef("Document")}}; הנתונים המאוחסניםנשמרים בכל מפגשי הדפדפן. localStorage   דומה ל-{{DOMxRef("Window.sessionStorage", "sessionStorage")}}, פרט לכך שבעוד תוקפם של הנתונים הנשמרים ב- localStorage אינו פג, נתונים הנשמרים ב-,sessionStorage נמחקים עם תום המפגש של הדף  —  כלומר, כשהדף נסגר.

+ +

יש לציין כי נתונים הנשמרים  ב-localStorage או ב-sessionStorage  הם מפורטים בפרוטוקול הדף.

+ +

המפתחות והערכים יביו תמיד מחרוזות (לתשומת לבך, בדומה לאובייקטים, מפתחות מטיפוס מספר שלם יומרו אוטומטית למחרוזות).

+ +

תחביר

+ +
myStorage = window.localStorage;
+ +

ערך

+ +

אובייקט מסוג {{DOMxRef("Storage")}} שניתן להשתמש בו לגישה לשטח האיחסון המקומי של המקור הנוכחי.

+ +

חריגות

+ +
+
SecurityError
+
הבקשה מפרה החלטות מדיניות, או שהמקור אינו  a valid scheme/host/port tuple (זה יכול לקרות אם המקור משתמש בסכמת (t file: או data:, למשל). לדוגמא, ייתכן שלמשתמש דפדפן המוגדר כך שישלול הרשאה לשמור נתונים כבלתי משתנים עבור מקור מסויים.
+
+ +

דוגמא

+ +

קטע הקוד הבא ניגש לאובייקט ה-{{DOMxRef("Storage")}} המקומי של המתחם הנוכחי , ומוסיף לו נתון באמצעות {{DOMxRef("Storage.setItem()")}}.

+ +
localStorage.setItem('myCat', 'Tom');
+ +

התחביר לקריאת נתון ה-localStorage הוא כדלקמן:

+ +
var cat = localStorage.getItem('myCat');
+ +

 התחביר למחיקת נתון ה-localStorage הוא כדלקמן:

+ +
localStorage.removeItem('myCat');
+ +

התחביר למחיקת כל הנתונים ב-localStorage  הוא כדלקמן:

+ +
// Clear all items
+localStorage.clear();
+
+ +
+

לתשומת לבך: נא לעיין במאמר  Using the Web Storage API   כדי לצפות בדוגמא השלמה.

+
+ +

מפרטים

+ + + + + + + + + + + + + + +
מפרטמצבהערה
{{SpecName("HTML WHATWG", "webstorage.html#dom-localstorage", "localStorage")}}{{Spec2("HTML WHATWG")}}
+ +

תאימות דפדפנים

+ + + +

{{Compat("api.Window.localStorage")}}

+ +

לעיון נוסף

+ + diff --git a/files/he/web/api/window/prompt/index.html b/files/he/web/api/window/prompt/index.html new file mode 100644 index 0000000000..a57610aa13 --- /dev/null +++ b/files/he/web/api/window/prompt/index.html @@ -0,0 +1,90 @@ +--- +title: Window.prompt() +slug: Web/API/Window/prompt +tags: + - דו-שיח + - הודעה + - פופ-אפ +translation_of: Web/API/Window/prompt +--- +
{{ApiRef("Window")}}
+ +

Window.prompt() - מציגה תיבת דו-שיח עם תוכן, כפתורי אישור וביטול ומאפשרת למשתמש להזין טקסט ומספרים.

+ +

תחביר

+ +
result = window.prompt(message);
+
+ +

פרמטרים

+ +
+
message {{optional_inline}}
+
מחרוזת שתופיע בגוף ההודעה.
+
+ +

דוגמאות

+ +
let sign = prompt("What's your sign?");
+
+if (sign.toLowerCase() == "scorpio") {
+  alert("Wow! I'm a Scorpio too!");
+}
+
+// there are many ways to use the prompt feature
+sign = window.prompt(); // open the blank prompt window
+sign = prompt();       //  open the blank prompt window
+sign = window.prompt('Are you feeling lucky'); // open the window with Text "Are you feeling lucky"
+sign = window.prompt('Are you feeling lucky', 'sure'); // open the window with Text "Are you feeling lucky" and default value "sure"
+ +

 

+ +

כאשר המשתמש לוחץ על לחצן האישור, הטקסט שהוזן בשדה הקלט מוחזר. במידה והמשתמש לוחץ על אישור מבלי להזין טקסט, מחרוזת ריקה מוחזרת. במידה והמשתמש לוחץ על לחצן ביטול, פונקציה זו מחזירה null.

+ +

ההודעה הנ"ל מופיעה כדלקמן (בדפדפן Chrome במערכת הפעלה OS X):

+ +

 

+ +

prompt() dialog in Chrome on OS X

+ +

הערות

+ +

 

+ +

תיבת הדו-שיח מכילה תיבת טקסט בת שורה אחת, לחצני ביטול ואישור ומחזירה את הטקסט שהמשתמש הזין בתיבת הטקסט. תיבות דו-שיח מונעות מהמשתמש גישה לממשק התוכנית עד אשר היא תיסגר.

+ +

יש לשים לב שהערך המחוזר מהשתמש יהיה מחרוזת. במידה והתשובה שלו צריכה להיות מספר, יש להמיר את הערך למספר.

+ +

 

+ +
const aNumber = Number(window.prompt("Type a number", ""));
+ +

מפרט

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'timers-and-user-prompts.html#dom-prompt', 'prompt()')}}{{Spec2('HTML WHATWG')}} 
+ +

תאימות דפדפן

+ + + +

{{Compat("api.Window.prompt")}}

+ +

ראה גם

+ + diff --git a/files/he/web/api/xmlhttprequest/index.html b/files/he/web/api/xmlhttprequest/index.html new file mode 100644 index 0000000000..8a5c739854 --- /dev/null +++ b/files/he/web/api/xmlhttprequest/index.html @@ -0,0 +1,172 @@ +--- +title: XMLHttpRequest +slug: Web/API/XMLHttpRequest +tags: + - AJAX + - API + - Communication + - HTTP + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web + - XHR + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest +--- +
{{APIRef("XMLHttpRequest")}}
+ +

Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in Ajax programming.

+ +

{{InheritanceDiagram(650, 150)}}

+ +

Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML, and it supports protocols other than HTTP (including file and ftp).

+ +

If your communication needs to involve receiving event data or message data from a server, consider using server-sent events through the {{domxref("EventSource")}} interface. For full-duplex communication, WebSockets may be a better choice.

+ +

Constructor

+ +
+
{{domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}}
+
The constructor initializes an XMLHttpRequest. It must be called before any other method calls.
+
+ +

Properties

+ +

This interface also inherits properties of {{domxref("XMLHttpRequestEventTarget")}} and of {{domxref("EventTarget")}}.

+ +
+
{{domxref("XMLHttpRequest.onreadystatechange")}}
+
An {{domxref("EventHandler")}} that is called whenever the readyState attribute changes.
+
{{domxref("XMLHttpRequest.readyState")}} {{readonlyinline}}
+
Returns an unsigned short, the state of the request.
+
{{domxref("XMLHttpRequest.response")}} {{readonlyinline}}
+
Returns an {{domxref("ArrayBuffer")}}, {{domxref("Blob")}}, {{domxref("Document")}}, JavaScript object, or a {{domxref("DOMString")}}, depending on the value of {{domxref("XMLHttpRequest.responseType")}}. that contains the response entity body.
+
{{domxref("XMLHttpRequest.responseText")}} {{readonlyinline}}
+
Returns a {{domxref("DOMString")}} that contains the response to the request as text, or null if the request was unsuccessful or has not yet been sent.
+
{{domxref("XMLHttpRequest.responseType")}}
+
Is an enumerated value that defines the response type.
+
{{domxref("XMLHttpRequest.responseURL")}} {{readonlyinline}}
+
Returns the serialized URL of the response or the empty string if the URL is null.
+
{{domxref("XMLHttpRequest.responseXML")}} {{readonlyinline}}
+
Returns a {{domxref("Document")}} containing the response to the request, or null if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML.
+
{{domxref("XMLHttpRequest.status")}} {{readonlyinline}}
+
Returns an unsigned short with the status of the response of the request.
+
{{domxref("XMLHttpRequest.statusText")}} {{readonlyinline}}
+
Returns a {{domxref("DOMString")}} containing the response string returned by the HTTP server. Unlike {{domxref("XMLHTTPRequest.status")}}, this includes the entire text of the response message ("200 OK", for example).
+
+ +
+

Note: According to the HTTP/2 specification (8.1.2.4 Response Pseudo-Header Fields), HTTP/2 does not define a way to carry the version or reason phrase that is included in an HTTP/1.1 status line.

+
+ +
+
{{domxref("XMLHttpRequest.timeout")}}
+
Is an unsigned long representing the number of milliseconds a request can take before automatically being terminated.
+
{{domxref("XMLHttpRequestEventTarget.ontimeout")}}
+
Is an {{domxref("EventHandler")}} that is called whenever the request times out. {{gecko_minversion_inline("12.0")}}
+
{{domxref("XMLHttpRequest.upload")}} {{readonlyinline}}
+
Is an {{domxref("XMLHttpRequestUpload")}}, representing the upload process.
+
{{domxref("XMLHttpRequest.withCredentials")}}
+
Is a {{domxref("Boolean")}} that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies or authorization headers.
+
+ +

Non-standard properties

+ +
+
{{domxref("XMLHttpRequest.channel")}}{{ReadOnlyInline}}
+
Is a {{Interface("nsIChannel")}}. The channel used by the object when performing the request.
+
{{domxref("XMLHttpRequest.mozAnon")}}{{ReadOnlyInline}}
+
Is a boolean. If true, the request will be sent without cookie and authentication headers.
+
{{domxref("XMLHttpRequest.mozSystem")}}{{ReadOnlyInline}}
+
Is a boolean. If true, the same origin policy will not be enforced on the request.
+
{{domxref("XMLHttpRequest.mozBackgroundRequest")}}
+
Is a boolean. It indicates whether or not the object represents a background service request.
+
{{domxref("XMLHttpRequest.mozResponseArrayBuffer")}}{{gecko_minversion_inline("2.0")}} {{obsolete_inline("6")}} {{ReadOnlyInline}}
+
Is an ArrayBuffer. The response to the request, as a JavaScript typed array.
+
{{domxref("XMLHttpRequest.multipart")}}{{obsolete_inline("22")}}
+
This Gecko-only feature, a boolean, was removed in Firefox/Gecko 22. Please use Server-Sent Events, Web Sockets, or responseText from progress events instead.
+
+ +

Event handlers

+ +

onreadystatechange as a property of the XMLHttpRequest instance is supported in all browsers.

+ +

Since then, a number of additional event handlers have been implemented in various browsers (onload, onerror, onprogress, etc.). See Using XMLHttpRequest.

+ +

More recent browsers, including Firefox, also support listening to the XMLHttpRequest events via standard addEventListener() APIs in addition to setting on* properties to a handler function.

+ +

Methods

+ +
+
{{domxref("XMLHttpRequest.abort()")}}
+
Aborts the request if it has already been sent.
+
{{domxref("XMLHttpRequest.getAllResponseHeaders()")}}
+
Returns all the response headers, separated by CRLF, as a string, or null if no response has been received.
+
{{domxref("XMLHttpRequest.getResponseHeader()")}}
+
Returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn't exist in the response.
+
{{domxref("XMLHttpRequest.open()")}}
+
Initializes a request. This method is to be used from JavaScript code; to initialize a request from native code, use openRequest() instead.
+
{{domxref("XMLHttpRequest.overrideMimeType()")}}
+
Overrides the MIME type returned by the server.
+
{{domxref("XMLHttpRequest.send()")}}
+
Sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent.
+
{{domxref("XMLHttpRequest.setRequestHeader()")}}
+
Sets the value of an HTTP request header. You must call setRequestHeader()after open(), but before send().
+
+ +

Non-standard methods

+ +
+
{{domxref("XMLHttpRequest.init()")}}
+
Initializes the object for use from C++ code.
+
+ +
Warning: This method must not be called from JavaScript.
+ +
+
{{domxref("XMLHttpRequest.openRequest()")}}
+
Initializes a request. This method is to be used from native code; to initialize a request from JavaScript code, use open() instead. See the documentation for open().
+
{{domxref("XMLHttpRequest.sendAsBinary()")}}{{deprecated_inline()}}
+
A variant of the send() method that sends binary data.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}Live standard, latest version
+ +

Browser compatibility

+ + + +

{{Compat("api.XMLHttpRequest")}}

+ +

See also

+ + diff --git a/files/he/web/css/index.html b/files/he/web/css/index.html new file mode 100644 index 0000000000..55679b0c8b --- /dev/null +++ b/files/he/web/css/index.html @@ -0,0 +1,97 @@ +--- +title: 'CSS: גיליונות סגנון מדורגים' +slug: Web/CSS +translation_of: Web/CSS +--- +
{{CSSRef}}
+ +

Cascading Style Sheets (CSS) is a stylesheet language used to describe the presentation of a document written in HTML or XML (including XML dialects such as SVG, MathML or {{Glossary("XHTML", "", 1)}}). CSS describes how elements should be rendered on screen, on paper, in speech, or on other media.

+ +

CSS is one of the core languages of the open Web and is standardized across Web browsers according to the W3C specification. Developed in levels, CSS1 is now obsolete, CSS2.1 is a recommendation, and CSS3, now split into smaller modules, is progressing on the standardization track.

+ +
+ + +
+
+

Tutorials

+ +

Our CSS Learning Area features multiple modules that teach CSS from the ground up — no previous knowledge required.

+ +
+
Introduction to CSS
+
This module starts with the basics of how CSS works, including selectors and properties, writing CSS rules, applying CSS to HTML, how to specify length, color, and other units in CSS, cascade and inheritance, box model basics, and debugging CSS.
+
Styling text
+
This module discusses text styling fundamentals, including setting fonts, boldness, italics, line and letter spacing, text drop shadows, and other text properties. This module finishes with applying custom fonts to your page, and styling lists and links.
+
Styling boxes
+
This module looks at styling boxes, one of the fundamental steps towards laying out a web page. In this module we recap the box model, then look at controlling box layouts by setting margins, borders, and padding, custom background colors, images and other features, and fancy features such as drop shadows and filters on boxes.
+
CSS layout
+
At this point we've already looked at CSS fundamentals, how to style text, and how to style and manipulate the boxes that your content sits inside. Now it's time to look at how to place your boxes in the right place in relation to the viewport, and one another. We have covered the necessary prerequisites so you can now dive deep into CSS layout, looking at different display settings, traditional layout methods involving float and positioning, and newfangled layout tools like flexbox.
+
+
+ +
+

Reference

+ + + +

Cookbook

+ +

The CSS layout cookbook aims to bring together recipes for common layout patterns, things you might need to implement in your own sites. In addition to providing code you can use as a starting point in your projects, these recipes highlight the different ways layout specifications can be used, and the choices you can make as a developer.

+ +

Tools for CSS development

+ + + +

Meta bugs

+ +
    +
  • Firefox: {{bug(1323667)}}
  • +
+
+
+
+ +

See also

+ + diff --git a/files/he/web/css/position/index.html b/files/he/web/css/position/index.html new file mode 100644 index 0000000000..0abe4c2b87 --- /dev/null +++ b/files/he/web/css/position/index.html @@ -0,0 +1,274 @@ +--- +title: 'position: מיקומים' +slug: Web/CSS/position +tags: + - Position + - css positions + - מיקום + - מיקומים ב-CSS +translation_of: Web/CSS/position +--- +
{{CSSRef}}
+ +
מיקומים הינם חוקי CSS המאפשרים לסדר אלמנטים שונים ולשלוט באופן התצוגה שלהם באמצעות מאפיינים שונים:
+ +
{{Cssxref("top")}} ,{{Cssxref("right")}}, {{Cssxref("bottom")}} {{Cssxref("left")}}
+ +
 
+ +
{{EmbedInteractiveExample("pages/css/position.html")}}
+ + + +
+
+

סוגי מיקומים

+
+
+

אלמנט ממוקם הוא אלמנט שערכו המחושב הוא ערך יחסי (relative), מוחלט (absolute), קבוע (fixed) או דביק (sticky) וכל דבר שאינו סטטי (static).

+
+
+ +
{{csssyntax}}
+ +
+
static
+
זהו מאפיין ברירת המחדל הממקם את האלמנט בהתאם לכללים הסטנדרטים של הדף, כמו כן למאפיין {{cssxref("z-index")}} אין השפעה על סדר הדף.
+
relative
+
האלמנט ממוקם בהתאם לזרימה הרגילה של המסמך ולאחר מכן מזיז את עצמו באמצעות הערכים top, right, bottomleft. הזזתו אינה משפיע על מיקומם של מרכיבים אחרים ולכן, המרחב שניתן עבור האלמנט בפריסת הדף זהה לזה של המיקום הסטטי.
+
absolute
+
האלמנט מוסר מהזרימה הרגילה של המסמך, לא נוצר מרווח יחודי עבור האלמנט אותו הוא מייצג. האלמנט ממוקם ביחס לאלמנט relative הקרוב ביותר אליו, במידה ואין כזה הוא ימוקם באופן יחסי לאלמנט האב הראשון של המסמך. ניתן להזיז אותו באמצעות הערכים top, right, bottomleft.
+
fixed
+
האלמנט מוסר מהזרימה הרגילה של המסמך, לא נוצר מרווח יחודי עבור האלמנט אותו הוא מייצג. האלמנט ימוקם באופן קבוע ויחסי לאלמנט האב הראשון של המסמך. ניתן להזיז אותו באמצעות הערכים top, right, bottomleft.
+
sticky
+
האלמנט ממוקם בהתאם לזרימה הרגילה של המסמך ולאחר מכן מזיז את עצמו ביחס לאלמנט האב הקרוב ביותר אליו. ניתן להזיז אותו באמצעות הערכים top, right, bottom, left והתזוזה שלו אינה משפיעה על המיקום של שאר האלמנטים. כאשר משתמשים בתכונה זו יש לשים לב שבעת הגלילה האלמנט יסתיר אלמנטים אחרים שנמצאים מתחתיו.
+
+ +

דוגמאות

+ +

מיקום אלמנט באמצעות Relative 

+ +

HTML

+ +
<div class="box" id="one">One</div>
+<div class="box" id="two">Two</div>
+<div class="box" id="three">Three</div>
+<div class="box" id="four">Four</div>
+
+ +

CSS

+ +
.box {
+  display: inline-block;
+  width: 100px;
+  height: 100px;
+  background: red;
+  color: white;
+}
+
+#two {
+  position: relative;
+  top: 20px;
+  left: 20px;
+  background: blue;
+}
+
+ +

{{ EmbedLiveSample('Relative_positioning', '600px', '200px') }}

+ +

מיקום אלמנט באמצעות Absolute

+ +
<h1>Absolute positioning</h1>
+
+<p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p>
+
+<p class="positioned">By default we span 100% of the width of our parent element, and we are as tall as our child content. Our total width and height is our content + padding + border width/height.</p>
+
+<p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both.</p>
+
+<p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. Overflowing inline elements <span>wrap onto a new line if possible — like this one containing text</span>, or just go on to a new line if not, much like this image will do: <img src="https://mdn.mozillademos.org/files/13360/long.jpg"></p>
+ +
body {
+  width: 500px;
+  margin: 0 auto;
+}
+
+p {
+  background: aqua;
+  border: 3px solid blue;
+  padding: 10px;
+  margin: 10px;
+}
+
+span {
+  background: red;
+  border: 1px solid black;
+}
+
+.positioned {
+  position: absolute;
+  background: yellow;
+  top: 30px;
+  left: 30px;
+}
+ +

{{ EmbedLiveSample('Absolute_positioning', '100%', 420) }}

+ +

 

+ +

מיקום אלמנט באמצעות Fixed

+ +

HTML

+ +
<div class="outer">
+  <p>
+    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam congue tortor eget pulvinar lobortis.
+    Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nam ac dolor augue.
+    Pellentesque mi mi, laoreet et dolor sit amet, ultrices varius risus. Nam vitae iaculis elit.
+    Aliquam mollis interdum libero. Sed sodales placerat egestas. Vestibulum ut arcu aliquam purus viverra dictum vel sit amet mi.
+    Duis nisl mauris, aliquam sit amet luctus eget, dapibus in enim. Sed velit augue, pretium a sem aliquam, congue porttitor tortor.
+    Sed tempor nisl a lorem consequat, id maximus erat aliquet. Sed sagittis porta libero sed condimentum.
+    Aliquam finibus lectus nec ante congue rutrum. Curabitur quam quam, accumsan id ultrices ultrices, tempor et tellus.
+  </p>
+  <p>
+    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam congue tortor eget pulvinar lobortis.
+    Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nam ac dolor augue.
+    Pellentesque mi mi, laoreet et dolor sit amet, ultrices varius risus. Nam vitae iaculis elit.
+    Aliquam mollis interdum libero. Sed sodales placerat egestas. Vestibulum ut arcu aliquam purus viverra dictum vel sit amet mi.
+    Duis nisl mauris, aliquam sit amet luctus eget, dapibus in enim. Sed velit augue, pretium a sem aliquam, congue porttitor tortor.
+    Sed tempor nisl a lorem consequat, id maximus erat aliquet. Sed sagittis porta libero sed condimentum.
+    Aliquam finibus lectus nec ante congue rutrum. Curabitur quam quam, accumsan id ultrices ultrices, tempor et tellus.
+  </p>
+  <div class="box" id="one">One</div>
+</div>
+
+ +

CSS

+ +
.box {
+  width: 100px;
+  height: 100px;
+  background: red;
+  color: white;
+}
+
+#one {
+  position: fixed;
+  top: 80px;
+  left: 10px;
+  background: blue;
+}
+
+.outer {
+  width: 500px;
+  height: 300px;
+  overflow: scroll;
+  padding-left: 150px;
+}
+
+ +

{{ EmbedLiveSample('Fixed_positioning', '800px', '300px') }}

+ +

מיקום אלמנט באמצעות Sticky 

+ +

HTML

+ +
<dl>
+  <div>
+    <dt>A</dt>
+    <dd>Andrew W.K.</dd>
+    <dd>Apparat</dd>
+    <dd>Arcade Fire</dd>
+    <dd>At The Drive-In</dd>
+    <dd>Aziz Ansari</dd>
+  </div>
+  <div>
+    <dt>C</dt>
+    <dd>Chromeo</dd>
+    <dd>Common</dd>
+    <dd>Converge</dd>
+    <dd>Crystal Castles</dd>
+    <dd>Cursive</dd>
+  </div>
+  <div>
+    <dt>E</dt>
+    <dd>Explosions In The Sky</dd>
+  </div>
+  <div>
+    <dt>T</dt>
+    <dd>Ted Leo &amp; The Pharmacists</dd>
+    <dd>T-Pain</dd>
+    <dd>Thrice</dd>
+    <dd>TV On The Radio</dd>
+    <dd>Two Gallants</dd>
+  </div>
+</dl>
+
+ +

CSS

+ +
* {
+  box-sizing: border-box;
+}
+
+dl > div {
+  background: #FFF;
+  padding: 24px 0 0 0;
+}
+
+dt {
+  background: #B8C1C8;
+  border-bottom: 1px solid #989EA4;
+  border-top: 1px solid #717D85;
+  color: #FFF;
+  font: bold 18px/21px Helvetica, Arial, sans-serif;
+  margin: 0;
+  padding: 2px 0 0 12px;
+  position: -webkit-sticky;
+  position: sticky;
+  top: -1px;
+}
+
+dd {
+  font: bold 20px/45px Helvetica, Arial, sans-serif;
+  margin: 0;
+  padding: 0 0 0 12px;
+  white-space: nowrap;
+}
+
+dd + dd {
+  border-top: 1px solid #CCC;
+}
+
+ +

{{ EmbedLiveSample('Sticky_positioning', '500px', '300px') }}

+ +

מפרטים

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS2.1', 'visuren.html#propdef-position', 'position')}}{{Spec2('CSS2.1')}} 
{{SpecName('CSS3 Positioning','#position-property','position')}}{{Spec2('CSS3 Positioning')}}Adds sticky property value.
+ +

תאימות לדפדפן

+ + + +

{{Compat("css.properties.position")}}

diff --git a/files/he/web/guide/html/html5/index.html b/files/he/web/guide/html/html5/index.html new file mode 100644 index 0000000000..80107c9424 --- /dev/null +++ b/files/he/web/guide/html/html5/index.html @@ -0,0 +1,177 @@ +--- +title: HTML5 +slug: Web/Guide/HTML/HTML5 +tags: + - Guide + - HELP + - HTML + - HTML5 + - NeedsTranslation + - Overview + - TopicStub + - Web + - Web Development +translation_of: Web/Guide/HTML/HTML5 +--- +

HTML5 is the latest evolution of the standard that defines HTML. The term represents two different concepts:

+ + + +

Designed to be usable by all Open Web developers, this reference page links to numerous resources about HTML5 technologies, classified into several groups based on their function.

+ + + +
+

Semantics

+ +
+
Sections and outlines in HTML5
+
A look at the new outlining and sectioning elements in HTML5: {{HTMLElement("section")}}, {{HTMLElement("article")}}, {{HTMLElement("nav")}}, {{HTMLElement("header")}}, {{HTMLElement("footer")}} and {{HTMLElement("aside")}}.
+
Using HTML5 audio and video
+
The {{HTMLElement("audio")}} and {{HTMLElement("video")}} elements embed and allow the manipulation of new multimedia content.
+
Forms in HTML5
+
A look at improvements to web forms in HTML5: the constraint validation API, several new attributes, new values for the {{HTMLElement("input")}} attribute {{htmlattrxref("type", "input")}} and the new {{HTMLElement("output")}} element.
+
New semantic elements
+
Beside sections, media and forms elements, there are numerous new elements, like {{HTMLElement("mark")}}, {{HTMLElement("figure")}}, {{HTMLElement("figcaption")}}, {{HTMLElement("data")}}, {{HTMLElement("time")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}}, or {{HTMLElement("meter")}} and {{HTMLElement("main")}}, increasing the amount of valid HTML5 elements.
+
Improvement in {{HTMLElement("iframe")}}
+
Using the {{htmlattrxref("sandbox", "iframe")}}, {{htmlattrxref("seamless", "iframe")}}, and {{htmlattrxref("srcdoc", "iframe")}} attributes, authors can now be precise about the level of security and the wished rendering of an {{HTMLElement("iframe")}} element.
+
MathML
+
Allows directly embedding mathematical formulas.
+
Introduction to HTML5
+
This article introduces how to indicate to the browser that you are using HTML5 in your web design or web application.
+
HTML5-compliant parser
+
The parser, which turns the bytes of an HTML document into a DOM, has been extended and now precisely defines the behavior to use in all cases, even when faced with invalid HTML. This leads to far greater predictability and interoperability between HTML5-compliant browsers.
+
+ +

Connectivity

+ +
+
Web Sockets
+
Allows creating a permanent connection between the page and the server and to exchange non-HTML data through that means.
+
Server-sent events
+
Allows a server to push events to a client, rather than the classical paradigm where the server could send data only in response to a client's request.
+
WebRTC
+
This technology, where RTC stands for Real-Time Communication, allows connecting to other people and controlling videoconferencing directly in the browser, without the need for a plugin or an external application.
+
+ +

Offline & storage

+ +
+
Offline resources: the application cache
+
Firefox fully supports the HTML5 offline resource specification. Most others have offline resource support at some level.
+
Online and offline events
+
Firefox 3 supports WHATWG online and offline events, which let applications and extensions detect whether or not there's an active Internet connection, as well as to detect when the connection goes up and down.
+
WHATWG client-side session and persistent storage (aka DOM Storage)
+
Client-side session and persistent storage allows web applications to store structured data on the client side.
+
IndexedDB
+
IndexedDB is a web standard for the storage of significant amounts of structured data in the browser and for high performance searches on this data using indexes.
+
Using files from web applications
+
Support for the new HTML5 File API has been added to Gecko, making it possible for web applications to access local files selected by the user. This includes support for selecting multiple files using the {{HTMLElement("input")}} of type file HTML element's new multiple attribute. There also is FileReader.
+
+ +

Multimedia

+ +
+
Using HTML5 audio and video
+
The {{HTMLElement("audio")}} and {{HTMLElement("video")}} elements embed and allow the manipulation of new multimedia content.
+
WebRTC
+
This technology, where RTC stands for Real-Time Communication, allows connecting to other people and controlling videoconferencing directly in the browser, without the need for a plugin or an external application.
+
Using the Camera API
+
Allows using, manipulating, and storing an image from the computer's camera.
+
Track and WebVTT
+
The {{HTMLElement("track")}} element allows subtitles and chapters. WebVTT is a text track format.
+
+ +

3D, graphics & effects

+ +
+
Canvas Tutorial
+
Learn about the new {{HTMLElement("canvas")}} element and how to draw graphs and other objects in Firefox.
+
HTML5 text API for <canvas> elements
+
The HTML5 text API is now supported by {{HTMLElement("canvas")}} elements.
+
WebGL
+
WebGL brings 3D graphics to the Web by introducing an API that closely conforms to OpenGL ES 2.0 that can be used in HTML5 {{HTMLElement("canvas")}} elements.
+
SVG
+
An XML-based format of vectorial images that can directly be embedded in the HTML.
+
+
+ +
+ +
+

Performance & integration

+ +
+
Web Workers
+
Allows delegation of JavaScript evaluation to background threads, allowing these activities to prevent slowing down interactive events.
+
XMLHttpRequest Level 2
+
Allows fetching asynchronously some parts of the page, allowing it to display dynamic content, varying according to the time and user actions. This is the technology behind Ajax.
+
JIT-compiling JavaScript engines
+
The new generation of JavaScript engines is much more powerful, leading to greater performance.
+
History API
+
Allows the manipulation of the browser history. This is especially useful for pages loading interactively new information.
+
The contentEditable attribute: transform your website to a wiki!
+
HTML5 has standardized the contentEditable attribute. Learn more about this feature.
+
Drag and drop
+
The HTML5 drag and drop API allows support for dragging and dropping items within and between web sites. This also provides a simpler API for use by extensions and Mozilla-based applications.
+
Focus management in HTML
+
The new HTML5 activeElement and hasFocus attributes are supported.
+
Web-based protocol handlers
+
You can now register web applications as protocol handlers using the navigator.registerProtocolHandler() method.
+
requestAnimationFrame
+
Allows control of animations rendering to obtain optimal performance.
+
Fullscreen API
+
Controls the usage of the whole screen for a Web page or application, without the browser UI displayed.
+
Pointer Lock API
+
Allows locking the pointer to the content, so games and similar applications don't lose focus when the pointer reaches the window limit.
+
Online and offline events
+
In order to build a good offline-capable web application, you need to know when your application is actually offline. Incidentally, you also need to know when your application has returned to an online status again.
+
+ +

Device access

+ +
+
Using the Camera API
+
Allows using, manipulating, and storing an image from the computer's camera.
+
Touch events
+
Handlers to react to events created by a user pressing touch screens.
+
Using geolocation
+
Let browsers locate the position of the user using geolocation.
+
Detecting device orientation
+
Get the information when the device on which the browser runs changes orientation. This can be used as an input device (e.g., to make games that react to the position of the device) or to adapt the layout of a page to the orientation of the screen (portrait or landscape).
+
Pointer Lock API
+
Allows locking the pointer to the content, so games and similar application don't lose focus when the pointer reaches the window limit.
+
+ +

Styling

+ +

CSS has been extended to be able to style elements in a much more complex way. This is often referred as CSS3, though CSS is not a monolithic specification any more and the different modules are not all at level 3: some are at level 1 and others at level 4, with all the intermediate levels covered.

+ +
+
New background styling features
+
It is now possible to put a shadow to a box, using {{cssxref("box-shadow")}} and multiple backgrounds can be set.
+
More fancy borders
+
Not only it is now possible to use images to style borders, using {{cssxref("border-image")}} and its associated longhand properties, but rounded borders are supported via the {{cssxref("border-radius")}} property.
+
Animating your style
+
Using CSS Transitions to animate between different states or using CSS Animations to animate parts of the page without a triggering event, you can now control mobile elements on your page.
+
Typography improvement
+
Authors have better control to reach better typography. They can control {{cssxref("text-overflow")}} and hyphenation, but also can add a shadow to it or control more precisely its decorations. Custom typefaces can be downloaded and applied thanks to the new {{cssxref("@font-face")}} at-rule.
+
New presentational layouts
+
In order to improve the flexibility of designs, two new layouts have been added: the CSS multi-column layout, and the CSS flexible box layout.
+
+
+
+ +

 

diff --git a/files/he/web/guide/index.html b/files/he/web/guide/index.html new file mode 100644 index 0000000000..e6e9e81592 --- /dev/null +++ b/files/he/web/guide/index.html @@ -0,0 +1,62 @@ +--- +title: מדריך למפתח אינטרנט +slug: Web/Guide +tags: + - Guide + - Landing + - NeedsTranslation + - TopicStub + - Web +translation_of: Web/Guide +--- +

מאמרים אלה מספקים עזרה לגבי שימוש בטכנלוגיות אינטרנט ו- API מסוימים.

+ +
+
+
+
אזור לימוד HTML
+
HTML (שפת תגיות לתמליל-על או HyperText Markup Language) הינה שפת הליבה של כמעט כל תוכן הרשת. מרבית הדברים על המסך בדפדפן שלך מתוארים בבסיסם על-ידי שימוש ב- HTML.
+
אזור לימוד CSS
+
CSS (גליונות סגנון מדורגים, או Cascading Style Sheets stylesheet) הינה שפה המשמשת להגדיר תצוגת מסמך HTML.
+
מדריך אירועים (Events) למפתח
+
אירועים (Events) מתייחסים לשני דברים:
+ תבנית עיצוב המשמשת לטיפול אסינכרוני במקרים שונים המתרחשים במהלך חיי עמוד האינטרנט;
+ והשיום (naming), אפיון והשימוש במספר גדול של מקרים מסוגים שונים.
+
AJAX
+
AJAX הוא מונח המגדיר קבוצת טכנולוגיות המאפשרות לאפליקציות רשת לבצע עדכונים מהירים ומצטברים לממשק המשתמש ללא טעינה מחדש של כל העמוד. דבר זה הופך את האפליקציה למהירה ותגובתית יותר לפעולות המשתמש.
+
גרפיקה ברשת
+
אתרי אינטרנט ואפליקציות מודרניות זקוקים לעתים להציג גרפיקה עם רמות תחכום שונות.
+
מדריך ל- API ברשת
+
רשימה של כל ה- API האינטרנטיים, ומה הם עושים.
+
ג'אווה-סקריפט (JavaScript)
+
JavaScript היא שפת תסריט (סקריפטינג) חזקה, המשמשת ליצירת אפליקציות באינטרנט.
+
לוקליזציה וקידוד תווים
+
Browsers process text as Unicode internally. However, a way of representing characters in terms of bytes (character encoding) is used for transferring text over the network to the browser. The HTML specification recommends the use of the UTF-8 encoding (which can represent all of Unicode), and regardless of the encoding used requires Web content to declare that encoding.
+
פיתוח אינטרנט למובייל
+
This article provides an overview of some of the main techniques needed to design web sites that work well on mobile devices. If you're looking for information on Mozilla's Firefox OS project, see the Firefox OS page. Or you might be interested in details about Firefox for Android.
+
+
+ +
+
+
אפליקציות אינטרנט מתקדמות (PWA)
+
Progressive web apps (PWAs) use modern web APIs along with traditional progressive enhancement strategy to create cross-platform web applications. These apps work everywhere and provide several features that give them the same user experience advantages as native apps. This set of guides tells you all you need to know about PWAs.
+
אופטימיזציות וביצועים
+
When building modern web apps and sites, it's important to make your content work quickly and efficiently. This lets it perform effectively for both powerful desktop systems and weaker handheld devices.
+
ניתוח וסריאליזציה של XML
+
פלטפורמת הרשת מספקת שיטות שונות לניתוח וסריאליזציה (סדרות) של XML, כל אחת מהן עם יתרונותיה וחסרונותיה.
+
פורמט גופן אינטרנט פתוח (WOFF, Web Open Font Format)
+
WOFF (Web Open Font Format) הוא תצורת קובץ גופן (פונט) זמינה לשימוש ברשת בחינם.
+
שימוש באובייקט FormData
+
אובייקט FormData מאפשר להדר אוסף של זוגות מפתח/ערך (key/value), כדי לשלוח בקשת XMLHttpRequest. הוא מיועד בעיקר לשלוחת פרטי טופס, אבל ניתן להשתמש בו באופן נפרד מטפסים, כדי לשלוח מידע. התשדורת נעשית באותה תצורה כמו שמתודת submit() שולחת טופס שהקידוד שלו הוא "multipart/form-data".
+
מילון מלים
+
מגדיר מספר מונחים טכניים הקשורים לרשת ולאינטרנט.
+
+
+
+ +

ראה גם

+ + diff --git a/files/he/web/guide/localizations_and_character_encodings/index.html b/files/he/web/guide/localizations_and_character_encodings/index.html new file mode 100644 index 0000000000..7ab8aa2ba4 --- /dev/null +++ b/files/he/web/guide/localizations_and_character_encodings/index.html @@ -0,0 +1,62 @@ +--- +title: התאמות למיקומים וקידוד תווים +slug: Web/Guide/Localizations_and_character_encodings +tags: + - HTML + - התאמה למיקום + - צורך בעבודת markup + - קידוד תווים +translation_of: Web/Guide/Localizations_and_character_encodings +--- +

דפדפנים מעבדים טקסט כיוניקוד בתוכם. אולם, דרך לייצג תווים במונחים של בייטים (קידוד תווים) משמשת להעברת טקסט על גבי הרשת לדפדפן. מפרט ה-HTML ממליץ על שימוש בקידוד UTF-8  (היכול לייצג את כל היוניקוד) ובלי קשר לקידוד שבשימוש מצריך כי בתוכן שברשת יוצהר באיזה קידוד השתמשו.

+ +

המאפיין {{htmlattrxref("charset", "meta")}}  של אלמנט ה-{{HTMLElement("meta")}} משמש לציין את קידוד התווים של הדף.

+ +

כדי לציין כי הדף משתמש, לדוגמאף בקידוד תווים UTF-8 (על פי ההמלצה), יש פשוט למקם את השורה הבאה בבלוק ה-{{HTMLElement("head")}}:

+ +
<meta charset="utf-8">
+
+ +

פרטים וקרבי הדפדפן

+ +

כשהקידוד מוצהר בתוכן הרשת כמתחייב ממפרט ה-HTML, פיירפוקס ישתמש בקידוד זה כדי להפוך את הבעעטם לייצוג הפנימי. לרוע המזל, שימוש ב-UTF-8 והצהרה כי UTF-8 הוא הקידוד שבשימוש לא היו תמיד הדרך הנפוצה להציע תוכן ברשת. בשנות ה-1990, היה נפוץ להשאיר את הקידוד לא מוצהר ולהשתמש בקידוד האופייני לאזור שלא היה מסוגל לייצג את כל היוניקוד.

+ +

פיירפוקס זקוק לקידוד לעת-מצוא שישמש לתוכן לא-תואם במתכונת הישנה שאינו מצהיר על קידודו. עבור רוב המיקומים, הקידוד לעת-מצוא הוא windows-1252 (הקרוי לעתים קרובות ISO-8859-1), שהוא הקידוד המתקבל כפלט מרוב אפילקציות ה-Windows בשנות ה-1990 וקבוצת על של הקידוד המתקבל כקלט מרוב יישומי היוניקס בשנות ה-1990 כפי שהתפרש באמריקה ובמערב אירופה.  אולם, קיימים מיקומים שבהם פרסום ברשת היה נפוץ כבר בשנות ה-1990 שקידוד windows-1252 לא התאים לשפה המקומית. במיקומים האלה תוכן במתכונת הישנה שאינו מצהיר את קידודו בופן טיפוסי מקודד באמצעות שיטת קידוד ישנה שאינה windows-1252. על מנת לעבוד עם תוכן המופיע במתכונת הישנה, חלק ממיקומי פיירפוקס זקוקים לקידוד לעת-מצוא שאינו windows-1252.

+ +

לרוע המזל, משמעות הדבר היא כי פונקציונליות פיירפוקס החשופה לרשת נבדלת במיקום וקשה לקרוא תוכן שנכתב במתכונת הישנה בכל המיקומים עם קידודים שונים לעת-מצוא. כדי להימנע היתקלות בבעיות במיקומים בהם פרסומים ברשת באו אחרי אימוץ UTF-8, מיקומים שאין בהם קידוד במתכונת הישנה שצצה מהפרקטיקות של שנות ה-1990, צריכים להשאיר את הקידוד לשעת-מצוא להיות windows-1252 כדי להקל על קריאת תוכן בעל מיקומים שונים ממיקומים שבהם הקידוד לעת מצוא הוא windows-1252. תוכן מקודד UTF-8 בשפת המקום, הנכתב כחדש, מצופה להצהיר על קידודו, שבמקרה זה הקידוד לעת-מצוא אינו חלק מעיבוד התוכן.

+ +

בנוסף, קיים מספר קטן של מיקומים בהם בשנות ה-1990 לא היה קידוד ברור מאליו האופייני לאזור, והזיהוי הראשוני מבין הקידודים בתמכונת הישנה הוצג לראשונה לדפדפני הרשת. לדבר  הייתה השפעה בכך שהמחברים ברשת היו תלויים בנוכחותו של זיהוי ראשוני, ולכן לפיירפוקס עדיין יש זיהוי ראשוני במיקומים אלה.

+ +

מציאת שמות קידוד קאנוניים

+ +

הטקסט שלהלן מתייחס לשמות קאנוניים של קידודים. השמות הקאנוניים הם הערכים מימין לשימן השוויון ב-unixcharset.properties.

+ +

ציון הקידוד לעת מצוא

+ +

מאז פיירפוקס 28, עבר זמנו של קטע זה, משום שההעדפה intl.charset.default אינה קיימת עוד. ההתאמה בין המיקומים לקידודים לעת מצוא  כעת בנויה לתוך  Gecko עצמו.

+ +

 הקידודים לעת מצוא מצויינים על ידי ההעדפהintl.charset.default ב- intl.properties. הן אמורות להיות מוגדרות כשמות הקאנוניים של הקידודים על פי המתכונת הישנה  שהכי צפוי שמשתמשי ההתאמות למיקומים   יפגשו בעת גלישה בתכנים במתכונת הישנה ברשת שאינם מצייתים לכללים ואינם מצהירים על קידודם.  יש לשים לב לכך שקידודים לעת מצוא כפי שהם מוגדרים על ידי המשפט הקודם לא בהכרח צריכים להיות מסוגלים לייצג את התווים הדרושים עבור שפת המיקום!

+ +

הקידוד לעת מצוא צריך להישאר מוגדר כ-windows-1252 עבור מיקומים מערב אירופאיים, מיקומים צפון-, מרכז- ודרום אמריקאיים, מיקומים אפריקאיים, מיקומים מקכז אסיאניים ומיקומים אוקיאניים. טיפוסית המיקום צריך להיות מוגדר אחרת מ-windows-1252 עבור  מיקומים מזרח אירופאיים, מיקומים מזרח תיכוניים ומיקומים צזרח אסיאניים.

+ +

על מנת להימנע מבעיות של יוצרי תוכן ברשת היוצרים תוכן מקודד UTF-8 בלי להצהיר כי UTF-8 הוא הקידוד שבשימוש ועל מנת להעלות למקסימום את היכולת של משתמשים לקרוא תוכן בעל מספר מיקומים, אין להגדיר את הקידוד לעת מצוא ל-UTF-8 לכל מיקום מוגדר כחדש. יש לשים לב שפיירפוקס כבר אינו שולח כותרת HTTP בשם Accept-Charset, כך שאין צורך לקחת בחשבון מה יפורסם ב-Accept-Charset כאשר מגדירים קידוד לעת מצוא.

+ +

למיקומים בהם הקידוד לעת מצוא הוא כעת  ISO-8859-1, הקידוד חייב להשתנות ל-windows-1252. ISO-8859-1 is decoded באותה דרך בדיוק כמו windows-1252, אך פיירפוקס עובר לטפל ב- windows-1252 כמו בתווית המועדפת עבור קידוד זה בהתאם ל- Encoding Standard.

+ +

עבור מיקומים שבהם ל- Internet Explorer נתח שוק יותר גדול מזה של  Firefox, הקידוד לעת מצוא צריך באופן טיפוסי להיות מוגדר לאותו ערך כמו ב-Internet Explorer. .ניתן לראות את הקידוד לעת מצוא שיש לדפדפן מסויים על ידי טעינת  test page. (יש לדאוג להשתמש בהתקנת דפדפן שנותרה לה הגדרות ברירת מחדל כשחוקרים זאת!)

+ +

עבור מיקומים שבהם ל- Firefox מתח שוק גדול יותר מזה של Internet Explorer, סביר להניח כי הטוב ביותר הוא לא לשנות את הקידוד לעת מצוא  אפילו אם אינו תואם את ההדרכה שניתנה לעיל . (לדוגמא, קידוד פיירפוקס עבור המיקומים  הפולני, ההונגרי והצ'כי  סביר שיהיה צריך להמשיך להיות   ISO-8859-2 למרות של-IE הגדרת מיקום לעת-מצוא שונה.)

+ +

כאשר בספק יש להשתמש ב-windows-1252 כקידוד לעת-מצוא.

+ +

ציון אופן הזיהוי ההתחלתי

+ +

אופן הזיהוי ההתחלתי מצויין בהעדפה  intl.charset.detector ב- intl.properties. הגדרה זו חייבת לישאר ריקה לכל המיקומים  שאינם הרוסי, האוקראיני והיפני.  . באף מצב אין לציין את הגלאי "universal". הוא אינו אוניברסלי למרות שמו!

+ +

חריגים עבור שפות מיעוט

+ +

אם ההתאמה למיקומים היא עבור שפת מיעוט והמשתמש הטיפוסי יודע לקרוא את שפת הרוב  של האזור והשתמשים קוראים תוכן אינטרנטי בשפת הרוב של האזר לעתים קרובות מואוד, יהא זה הולם לציין את הקידוד לעת מצוא ואת הזיהוי הראשוני להיות זהה לזה של ההתאמה למיקום עבור שפת הרוב של האזור,  לדוגמא, עבור הגדרת מיקום של שפת מיעוט ברוסיה, יהא הולם להעתיק רת הגדרות המיקום הרוסיות.

+ +

הפיכת מספר קידודים לניתנים לבחירה בקלות מתוך תפריט קידודי תווים

+ +

ההעדפה intl.charsetmenu.browser.static ב- intl.properties הופכת מספר קידודי תווים לזמינים בקלות רבה יותר בתפריט קידודי תווים בדפדפן. על הערך להיות רשימה מופרדת ע"י פסיקים של שמות קידודים קאנוניים.  על הרשימה לכלול לפחות את הקידודים לעת מצוא, את windows-1252 ואת UTF-8. למיקומים שבהם יש יותר מקידוד אחד מהדור הישן, על כל הקידודים האלה להיכלל. לדוגמא, הקידוד לעת מצוא עבור יפני הוא  Shift_JIS, אבל יש עוד קידודים מהדור הישן  : ISO-2022-JP ו- EUC-JP. לכן, יהיה הגיוני אם הרשימה תהיה Shift_JIS, EUC-JP, ISO-2022-JP, windows-1252, UTF-8.

diff --git a/files/he/web/guide/performance/index.html b/files/he/web/guide/performance/index.html new file mode 100644 index 0000000000..6c363e0a0c --- /dev/null +++ b/files/he/web/guide/performance/index.html @@ -0,0 +1,23 @@ +--- +title: אופטימיזציה וביצועים +slug: Web/Guide/Performance +tags: + - אופטימיזציה + - אינטרנט + - ביצועים + - נחיתה + - רשת +translation_of: Web/Guide/Performance +--- +

בעת בניית אתרים ואפליקציות אינטרנט מודרניים, חשוב לגרום לתוכן שלך לתפקד היטב. כלומר לגרום לו להיות מהיר ויעיל. דבר זה מאפשר לתפקד באופן אפקטיבי הן למשתמשי מערכת מחשבים נייחים חזקים, והן למכשירים ניידים פחות חזקיפ. קיימים מספר כלים זמינים לבדיקצת ביצועים של אתר או בלוג. הכלים הראויים ביותר לציון רשומים להלן.

+ + + +

המשאבים לעיל כוללים גם את שיטות העבודה המומלצות לשיפור ביצועים. חשוב לתת עדיפות לביצועים, תוך התחשבות בביצועי הרשת במהלך הפיתוח, כדי שמשתמשים יזכו לחווית המשתמש הטובה ביותר.

+ +

{{LandingPageListSubpages}}

diff --git a/files/he/web/html/element/a/index.html b/files/he/web/html/element/a/index.html new file mode 100644 index 0000000000..de79afa3e5 --- /dev/null +++ b/files/he/web/html/element/a/index.html @@ -0,0 +1,90 @@ +--- +title: ': תגית קישור' +slug: Web/HTML/Element/a +translation_of: Web/HTML/Element/a +--- +

{{HTMLRef}}

+ +

תגית <a> מוסיפה קישור טקסט/תמונה במסמך ה-HTML. זוהי תגית מסוג Inline המסמנת את האלמנט עצמו בלבד.

+ +

 

+ +

{{EmbedInteractiveExample("pages/tabbed/a.html", "tabbed-standard")}}

+ +

 

+ + + + + + + + + + + + + + + + + + + + +
קטגוריהתגיות Inline.
תוכן מורשהטקסטים, תמונות ומספרים +

 

+
תגיות הורים מורשותתגית זו מורשית להופיע בגוף המסמך אך אינה חייבת להיות כפופה בצורה ישירה אל תגית {{HTMLElement("body")}}.
ממשק DOM{{domxref("HTMLAnchorElement")}}
+ +

תארים

+ +

תגית זו נכללת ברשימת התארים הגלובליים.

+ +

href - משמש להוספת כתובת קישור.
+ target - קובע היכן יפתח הקישור (עמוד הנוכחי, כרטיסייה חדשה וכו').
+ id - מזהה המשמש לקישור פנימי בין עמודים.

+ +
+
+

דוגמא 1 - קישור סטנדרטי

+ +
<!-- anchor linking to external file -->
+<a href="https://www.mozilla.com/">
+External Link
+</a>
+
+
+
+

דוגמא 2 - קישור למזהה פנימי בעמוד

+ +
<!-- links to element on this page with id="attr-href" -->
+<a href="#attr-href">
+Description of Same-Page Links
+</a>
+
+
+
+
+

דוגמא 3 - תמונה לחיצה

+ +
<a href="https://developer.mozilla.org/en-US/" target="_blank">
+  <img src="https://mdn.mozillademos.org/files/6851/mdn_logo.png"
+       alt="MDN logo" />
+</a>
+
+
+
+

דוגמא 4 - קישור לדוא"ל

+ +
<a href="mailto:nowhere@mozilla.org">Send email to nowhere</a>
+
+
+
+ +

ראה גם

+ + diff --git a/files/he/web/html/element/address/index.html b/files/he/web/html/element/address/index.html new file mode 100644 index 0000000000..d7997e2296 --- /dev/null +++ b/files/he/web/html/element/address/index.html @@ -0,0 +1,77 @@ +--- +title: '
: תגית לסימון כתובת' +slug: Web/HTML/Element/address +tags: + - Address + - HTML + - כתובת +translation_of: Web/HTML/Element/address +--- +
{{HTMLRef}}
+ +

תגית <address> נועדה כדי להציג מידע ליצירת קשר אודות אדם יחיד או ארגון.

+ +

{{EmbedInteractiveExample("pages/tabbed/address.html", "tabbed-standard")}}

+ + + + + + + + + + + + + + + + + + + + +
קטגוריהתגיות לארגון תוכן.
תוכן מורשה +

<hgroup>
+ <h1-h6>
+ <article>
+ <aside>
+ <section>
+ <nav>
+ <header>
+ <footer>

+
תגיות הורים מורשותתגית זו מורשת להופיע בגוף המסמך אך אינה חייבת להיות כפופה בצורה ישירה אל תגית {{HTMLElement("body")}}.
ממשק DOM{{domxref("HTMLElement")}}
+ +

תארים

+ +

תגית זו נכללת ברשימת התארים הגלובליים.

+ +
+
+

דוגמא

+ +
<address>
+  You can contact author at <a href="http://www.somedomain.com/contact">
+  www.somedomain.com</a>.<br>
+  If you see any bugs, please <a href="mailto:webmaster@somedomain.com">
+  contact webmaster</a>.<br>
+  You may also want to visit us:<br>
+  Mozilla Foundation<br>
+  331 E Evelyn Ave<br>
+  Mountain View, CA 94041<br>
+  USA
+</address>
+
+
+
+ +

ראה גם

+ + diff --git a/files/he/web/html/element/applet/index.html b/files/he/web/html/element/applet/index.html new file mode 100644 index 0000000000..5c85cfaa83 --- /dev/null +++ b/files/he/web/html/element/applet/index.html @@ -0,0 +1,37 @@ +--- +title: ': הטמעה של ישומון ג''אווה בעמוד' +slug: Web/HTML/Element/applet +translation_of: Web/HTML/Element/applet +--- +
{{HTMLRef}}
+ +

תגית <applet> מטמיעה יישומון Java במסמך ה-HTML. אלמנט זה הוצא משימוש לטובת {{HTMLElement ("object")}}.

+ +

* זוהי תגית ישנה ואינה חלק משפת HTML גרסה 5, השימוש ביישומוני Java בדפדפני אינטרנט הופסק.

+ +

תארים

+ +
    +
  • {{htmlattrdef("align")}} -  מציינת את שם העמודה מאובייקט מקור הנתונים.
  • +
  • {{htmlattrdef("alt")}} - תכונה זו משמשת למיקום היישומון בדף ביחס לתוכן.
  • +
  • {{htmlattrdef("code")}} - תכונה זו מציינת את כתובת האתר של קובץ היישומון.
  • +
+ +
+
+

דוגמא

+ +
<applet code="game.class" align="left" archive="game.zip" height="250" width="350">
+  <param name="difficulty" value="easy">
+  <b>Sorry, you need Java to play this game.</b>
+</applet>
+
+
+
+ +

ראה גם

+ +
    +
  • {{HTMLElement("object")}}
  • +
  • {{HTMLElement("embed")}}
  • +
diff --git a/files/he/web/html/element/article/index.html b/files/he/web/html/element/article/index.html new file mode 100644 index 0000000000..f58e278fc5 --- /dev/null +++ b/files/he/web/html/element/article/index.html @@ -0,0 +1,102 @@ +--- +title: '
: תגית לסימון אזור תוכן' +slug: Web/HTML/Element/article +translation_of: Web/HTML/Element/article +--- +
{{HTMLRef}}
+ +

תגית <article> הינה עצמאית ומגדירה אזור תוכן במסמך ה-HTML.
+ התוכן שיוזן בין התגיות עשוי להיות כתבה, מאמר, תגובה או הודעה.

+ +

{{EmbedInteractiveExample("pages/tabbed/article.html", "tabbed-standard")}}

+ + + + + + + + + + + + + + + + + + + + +
קטגוריהתגיות לארגון תוכן.
תוכן מורשה +

<a>, <abbr>, <address>, <article>, <aside>, <audio>, <b>,<bdo>, <bdi>, <blockquote>, <br>, <button>, <canvas>, <cite>, <code>, <command>, <data>, <datalist>, <del>, <details>, <dfn>, <div>, <dl>, <em>, <embed>, <fieldset>, <figure>, <footer>, <form>, <h1>, <h2>, <h3>, <h4>, <h5>, <h6>, <header>, <hgroup>, <hr>, <i>, <iframe>, <img>, <input>, <ins>, <kbd>, <keygen>, <label>, <main>, <map>, <mark>, <math>, <menu>, <meter>, <nav>, <noscript>, <object>, <ol>, <output>, <p>, <pre>, <progress>, <q>, <ruby>, <s>, <samp>, <script>, <section>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <svg>, <table>, <template>, <textarea>, <time>, <ul>, <var>, <video>, <wbr>.

+
תגיות הורים מורשותתגית זו מורשת להופיע בגוף המסמך אך אינה חייבת להיות כפופה בצורה ישירה אל תגית {{HTMLElement("section")}}.
ממשק DOM{{domxref("HTMLElement")}}
+ +

תארים

+ +

תגית זו נכללת ברשימת התארים הגלובליים.

+ +
+
+

דוגמא

+ +
<article class="film_review">
+  <header>
+    <h2>Jurassic Park</h2>
+  </header>
+  <section class="main_review">
+    <p>Dinos were great!</p>
+  </section>
+  <section class="user_reviews">
+    <article class="user_review">
+      <p>Way too scary for me.</p>
+      <footer>
+        <p>
+          Posted on
+          <time datetime="2015-05-16 19:00">May 16</time>
+          by Lisa.
+        </p>
+      </footer>
+    </article>
+    <article class="user_review">
+      <p>I agree, dinos are my favorite.</p>
+      <footer>
+        <p>
+          Posted on
+          <time datetime="2015-05-17 19:00">May 17</time>
+          by Tom.
+        </p>
+      </footer>
+    </article>
+  </section>
+  <footer>
+    <p>
+      Posted on
+      <time datetime="2015-05-15 19:00">May 15</time>
+      by Staff.
+    </p>
+  </footer>
+</article>
+
+
+
+ +

הערות

+ +
    +
  • כותרת (<h1> - <h6>) משמשת לרוב כילד של האלמנט <article>.
  • +
  • ניתן להשתמש באלמנט <article> כפוסט או תגובה כהתייחסות לפוסט החיצוני.
  • +
  • ניתן להוסיף את פרטי המחבר באמצעות אלמנט <address>.
  • +
  • ניתן להוסיף תאריך ואת שעת הפרסום התוכן באמצעות מאפיין datetime של אלמנט <time>.
  • +
+ +

ראה גם

+ +
    +
  • {{HTMLElement("nav")}} 
  • +
  • {{HTMLElement("address")}} 
  • +
  • {{HTMLElement("aside")}} 
  • +
  • {{HTMLElement("h1")}} 
  • +
  • {{HTMLElement("hgroup")}}
  • +
diff --git a/files/he/web/html/element/aside/index.html b/files/he/web/html/element/aside/index.html new file mode 100644 index 0000000000..ae470009c2 --- /dev/null +++ b/files/he/web/html/element/aside/index.html @@ -0,0 +1,75 @@ +--- +title: '