在Bookmarklet中使用jQuery UI

Cam*_*mel 2 javascript jquery jquery-ui bookmarklet coffeescript

在CoffeeScript中,虽然此代码几乎与JavaScript相同:

tabs_html = "<div id='nm-container'><ul><li><a href='#tabs-1'>Guidelines</a></li><li><a href='#tabs-2'>Test</a></li></ul>
            <div id='tabs-1'><p>something1</p></div><div id='tabs-2'><p>something2</p></div></div>"
$("#nm-toolbar").append(tabs_html)
$("#nm-container").tabs()
Run Code Online (Sandbox Code Playgroud)

它不起作用.有趣的是,它在尝试最后一行时起作用:$("#nm-container").tabs()从控制台.我附上下面的完整代码.请注意,我正在使用CoffeeMarklet生成似乎仅适用于chrome的bookmarklet.

s1 = window.document.createElement('script')
s1.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'
window.document.body.appendChild(s1)

$ ->

    s2 = window.document.createElement('script')
    s2.src = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js'
    window.document.body.appendChild(s2)

    jqueryUIcss = window.document.createElement('link')
    jqueryUIcss.rel = 'stylesheet'
    jqueryUIcss.type = 'text/css'
    jqueryUIcss.href = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/themes/blitzer/jquery-ui.css'
    window.document.head.appendChild(jqueryUIcss)

    if $("#nm-toolbar").length == 0
        toolbar = "<div id='nm-toolbar'></div>"
        $("body").append(toolbar)
        $("#nm-toolbar").css({
            'background':               '#fafafa',
            'height':                   '500px',
            'width':                    '400px',
            'position':                 'fixed',
            'bottom':                   '0px',
            'right':                    '20px',
            'padding':                  '5px'
        })

        tabs_html = "<div id='nm-container'><ul><li><a href='#tabs-1'>Guidelines</a></li><li><a href='#tabs-2'>Test</a></li></ul>
            <div id='tabs-1'><p>something1</p></div><div id='tabs-2'><p>something2</p></div></div>"
        $("#nm-toolbar").append(tabs_html)
        $("#nm-container").tabs()
Run Code Online (Sandbox Code Playgroud)

Tre*_*ham 5

我怀疑问题是你是异步加载jQuery UI.这条线

window.document.body.appendChild(s2)
Run Code Online (Sandbox Code Playgroud)

开始加载jQuery UI,但是在jQuery UI必须加载之前你的代码仍在继续.这可以解释为什么tabs()代码中的调用失败,但是在脚本有时间加载之后,当你从控制台执行调用时它会成功.

您应该能够通过使其余代码从回调运行来解决此问题

s2.onreadystatechange = ->
  return unless @readyState is 'complete'
  # the rest of the code goes here
Run Code Online (Sandbox Code Playgroud)

编辑:就此而言,你真的应该做同样的事情s1,否则$ ->电话可能会失败.它成功的事实表明你在浏览器中缓存了jQuery,或者页面上已经有jQuery.您还应该使用noConflict以避免覆盖页面的现有jQuery版本.Acorn链接的Run jQuery Code Bookmarklet执行所有这些操作(并且以比此答案中的代码更交叉的浏览器方式).