Chrome extensions with jQuery

亡梦爱人 提交于 2019-12-22 18:14:04

问题


I downloaded http://code.google.com/chrome/extensions/samples.html#ea2894c41cb8e80a4433a3e6c5772dadce9be90d. I would like make it it jQuery, but if i do:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>

<script>
$("div").css('background-color', 'black');

$('.click').click(function(){
  chrome.tabs.executeScript(null,
    {code:"document.body.style.backgroundColor='" + $(this).attr('id') + "'"});
  window.close();
})
</script>
<div class="click" id="red">red</div>
<div class="click" id="blue">blue</div>
<div class="click" id="green">green</div>
<div class="click" id="yellow">yellow</div>

this not working. Nothing happens. Why?


回答1:


You didn't include the document ready handler, try this:

<script>
    $(function() {
        $("div").css('background-color', 'black');

        $('.click').click(function() {
            chrome.tabs.executeScript(null,
                {code:"document.body.style.backgroundColor='" + $(this).attr('id') + "'"});
            window.close();
        })
    });
</script>
<div class="click" id="red">red</div>
<div class="click" id="blue">blue</div>
<div class="click" id="green">green</div>
<div class="click" id="yellow">yellow</div>

Alternatively you can move your <script> tag to just before the </body> tag so that all HTML is loaded before the javascript.




回答2:


You need to include jQuery first, like

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

You should check the popup page console for errors.




回答3:


Wrap your jQuery in this:

<script type="text/javascript">
$(document).ready(function() {


});
</script>

So, your jQuery should look like this:

<script type="text/javascript">
$(document).ready(function() {

    // YOUR CODE GOES HERE

})
</script>


来源:https://stackoverflow.com/questions/9294928/chrome-extensions-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!