【问题标题】:anonymous function passed from PHP and set specific `this` reference从 PHP 传递的匿名函数并设置特定的 `this` 引用
【发布时间】:2009-06-13 17:58:26
【问题描述】:

我有一个带有静态函数的 PHP 类:

<? echo view::getUserSelector() ?>

哪些输出:

<div id="user_selector">
    <div class="user">
        <h1>Username1</h1>
        <a href="javascript:selectUser(this);">select</a>
    </div>
    <div class="user">
        <h1>Username2</h1>
        <a href="javascript:selectUser(this);">select</a>
    </div>
</div>

我需要做些什么才能做到这一点?:

<? echo view::getUserSelector(array('onSelect' => 'function() { alert(this.id); }')); ?>
  1. 如何将onSelect-值“添加”为div#user_selector 的函数?
  2. 如何使用this 引用作为div#user_select 来“调用”div#user_selector.onSelect()

Javascript:

function selectUser(anchor) {
    //remove all 'selected' classes from $user_selector child divs
    //add 'selected' class to parent div.user of anchor
}

【问题讨论】:

  • 您有冲突的要求:“我希望在 selectUser() 执行后执行此代码。...以及如何在 selectUser() 函数中执行此函数?”您不能同时在 in selectUser() 在 selectUser() 之后执行它。你能澄清一下你在找什么吗?
  • 你说得对,我重新表述了这个问题。谢谢
  • 由于您通常不能“选择”一个 div,您认为用户会做什么来“选择”它?
  • 这对我想要实现的目标并不重要,对吧?但是,在我从先前选择的 div 中删除了 'selected' 之后,我将一个类 'selected' (css) 添加到调用 selectUser() 函数的锚的父 div 中。

标签: php javascript jquery this


【解决方案1】:

在输出所有这些的 PHP 函数中,你可以在脚本标签中添加它,这会给你想要的(据我所知)。

<script type="text/javascript>
var uSelect = document.getElementById('user_select');
uSelect.onSelect = function() {
    alert(this.id);
}

function selectUser(anchor) {
    //remove all 'selected' classes from $user_selector child divs
    //add 'selected' class to parent div.user of anchor
    uSelect.onSelect();
}
</script>

但是,我想指出的另一个资源是,如果您想简单地声明函数并且想知道如何将任何给定对象分配为其中的“this”,Javascript 函数必须使用方法 @987654321@ 和 @ 987654325@.

例如:你也可以尝试这样的事情。

<script type="text/javascript>
var onSelect = function() {
    alert(this.id);
}

function selectUser(anchor) {
    //remove all 'selected' classes from $user_selector child divs
    //add 'selected' class to parent div.user of anchor
    var node = anchor;
    while(node && node.parentNode) {
        if(node.getAttribute('id') == 'user_select') {
            //apply(thisRef, argsArray)
            //call(thisRef, arg1, arg2 [...])

            onSelect.apply(node);
            break;
        }
        node = node.parentNode;
    }
}
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    • 2012-03-22
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 2019-11-23
    相关资源
    最近更新 更多