如何通过锚链接传递`this`对象并将其转换为jQuery对象?

SIS*_*SYN 1 javascript jquery this

我正在努力解决一些我正在努力简化的问题.单击链接时,我希望通过jQuery更新其CSS.我的主要问题是,如何将Javascript的this对象转换为jQuery对象以便于处理?

这是我的代码的样子:

<!-- HTML -->
<a href="javascript:load('page.php', this);">load some page</a>
<a href="javascript:load('other.php', this);">load other page</a>

// JS
function load(url, linkObj) {
    loadPageWithURL(url);
    $(linkObj).css('text-decoration', 'underline');
}
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用.显然,当选择一个链接时,我所做的不仅仅是下划线,而是你明白了.我使用this错误还是只是将原始JS对象转换为jQuery识别的对象?

Pau*_*aul 7

该函数可以正常工作($(linkObj)是正确的),但是你的脚本href代替on onclick属性.所以它永远不会执行.

更改:

<a href="load('page.php', this);">load some page</a>
<a href="load('other.php', this);">load other page</a>
Run Code Online (Sandbox Code Playgroud)

至:

<a href="#" onclick="load('page.php', this); return false;">load some page</a>
<a href="#" onclick="load('other.php', this); return false;">load other page</a>
Run Code Online (Sandbox Code Playgroud)


Roc*_*mat 6

不要使用内联事件!使用jQuery绑定它们.

<a class="load" href="page.php">load some page</a>
<a class="load" href="other.php">load other page</a>
Run Code Online (Sandbox Code Playgroud)

然后在JavaScript中

$(function(){
    $('.load').click(function(e){
        e.preventDefault();

        loadPageWithURL(this.href);
        $(this).css('text-decoration', 'underline');
    });
});
Run Code Online (Sandbox Code Playgroud)

更新:如果在加载页面后添加新链接,则需要使用:

$(function(){
    $(document).on('click', '.load', function(e){
        e.preventDefault();

        loadPageWithURL(this.href);
        $(this).css('text-decoration', 'underline');
    });
});
Run Code Online (Sandbox Code Playgroud)