首页 \ 问答 \ 为什么javascript发送元素到我的事件处理程序,当该元素没有事件?(Why is javascript sending an element to my event handler, when that element has no event?)

为什么javascript发送元素到我的事件处理程序,当该元素没有事件?(Why is javascript sending an element to my event handler, when that element has no event?)

这个html:

<span id="mySpan"><img src="images/picture.png" alt="Some nice alt text" />
 Link text</span>

该JavaScript采用包含图像和文本的跨度,然后使其可点击:

spanVar = document.getElementById("mySpan");
spanVar.addEventListener("click", myEvent, false);

function myEvent(e){
 var obj = e.target;
}

如果我点击“链接文本”,那么myEvent()中的obj就是跨度。 如果我点击图片,那么obj就是图片元素! 图像本身没有事件。 那为什么它不是总是传递给事件处理程序的跨度?

顺便说一句,这是为了简单起见,它只能在Firefox中起作用。

另外,如果你能更加连贯地形成它,请随时编辑我的问题标题。


This html:

<span id="mySpan"><img src="images/picture.png" alt="Some nice alt text" />
 Link text</span>

This javascript takes the span containing the image and text, then makes it clickable:

spanVar = document.getElementById("mySpan");
spanVar.addEventListener("click", myEvent, false);

function myEvent(e){
 var obj = e.target;
}

If I click on the "Link text," then the obj in myEvent() is the span. If I click on the image, then the obj is the image element! The image itself has no event. So why isn't it always the span that gets passed to the event handler?

This is trimmed down so that it only works in Firefox for the sake of simplicity, by the way.

Also, please feel free to edit my question title if you can formualate it more coherently.


原文:https://stackoverflow.com/questions/4035805
更新时间:2023-05-04 08:05

最满意答案

我不确定您的PlayingCard类是如何编码的,但您的问题似乎有很大一部分来自其设计。 以这个实现为例:

PlayingCard

public class PlayingCard : IComparable<PlayingCard>
{
    private int value;
    private int suit;
    private Bitmap cardImage;

    public int Value => value;
    public string ValueName => ValueToName(value);

    public int Suit => suit;
    public string SuitName => SuitToName(suit);

    public Bitmap CardImage => cardImage;

    public PlayingCard(int value, int suit, Bitmap cardImage)
    {
        this.value = value;
        this.suit = suit;
        this.cardImage = cardImage;
    }

    private string ValueToName(int n)
    {
        switch (n)
        {
            case 0:
                return "Ace";
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
                return (n+1).ToString();
            case 10:
                return "Jack";
            case 11:
                return "Queen";
            case 12:
                return "King";
            default:
                throw new ArgumentException("Unrecognized card value.");

        }
    }

    private string SuitToName(int s)
    {
        switch (s)
        {
            case 0:
                return "Clubs";
            case 1:
                return "Diamonds";
            case 2:
                return "Spades";
            case 3:
                return "Hearts";
            default:
                throw new ArgumentException("Unrecognized card suit");
        }
    }

    public int CompareTo(PlayingCard other)
    {
        int result = this.Suit.CompareTo(other.Suit);

        if (result != 0)
            return result;

        return this.Value.CompareTo(other.Value);
    }

    public override string ToString()
    {
        return String.Format("{0} of {1}", ValueName, SuitName);
    }
}

它将所有的比较和价值转换编码在其中,因此您不必担心创建高度专业化的方法来进行无关转换。 你可以像这样在一个套牌中使用它:

数组实现

// How to initialize deck
PlayingCard[] deck = Enumerable.Range(0, 52)
                        .Select(x => new PlayingCard(x % 13, x / 13, imageListCards[x]))
                        .ToArray();


// How to shuffle deck
Random r = new Random();
Array.Sort(deck, (a, b) => r.Next(0, 2) == 0 ? -1 : 1);

// How to reset deck
Array.Sort(deck);

// How to display top five cards
pictureBox_Card1.Image = deck[0].CardImage;
pictureBox_Card2.Image = deck[1].CardImage;
pictureBox_Card3.Image = deck[2].CardImage;
pictureBox_Card4.Image = deck[3].CardImage;
pictureBox_Card5.Image = deck[4].CardImage;

清单实施

// How to initialize deck
List<PlayingCard> deck = Enumerable.Range(0, 52)
                        .Select(x => new PlayingCard(x % 13, x / 13, imageListCards[x]))
                        .ToList();


// How to shuffle deck
Random r = new Random();
deck.Sort((a, b) => r.Next(0, 2) == 0 ? -1 : 1);

// How to reset deck
deck.Sort();

// How to display top five cards
pictureBox_Card1.Image = deck[0].CardImage;
pictureBox_Card2.Image = deck[1].CardImage;
pictureBox_Card3.Image = deck[2].CardImage;
pictureBox_Card4.Image = deck[3].CardImage;
pictureBox_Card5.Image = deck[4].CardImage;

编辑:

手动混洗

如果你想手动进行洗牌,有一个简单的算法叫做Fisher-Yates Shuffle ,它可以做到这一点:

private static Random r = new Random();
static void Shuffle<T>(T[] array)
{
    for (int i = 0; i < array.Length; i++)
    {
        int idx = r.Next(i, array.Length);
        T temp = array[idx];
        array[idx] = array[i];
        array[i] = temp;
    }
}

(列表实施)

private static Random r = new Random();
static void Shuffle<T>(List<T> list)
{
    for (int i = 0; i < list.Count; i++)
    {
        int idx = r.Next(i, list.Count);
        T temp = list[idx];
        list[idx] = list[i];
        list[i] = temp;
    }
}

I'm not sure how your PlayingCard class is coded, but it seems like a large portion of your problems stem from its design. Take this implementation for example:

PlayingCard Class

public class PlayingCard : IComparable<PlayingCard>
{
    private int value;
    private int suit;
    private Bitmap cardImage;

    public int Value => value;
    public string ValueName => ValueToName(value);

    public int Suit => suit;
    public string SuitName => SuitToName(suit);

    public Bitmap CardImage => cardImage;

    public PlayingCard(int value, int suit, Bitmap cardImage)
    {
        this.value = value;
        this.suit = suit;
        this.cardImage = cardImage;
    }

    private string ValueToName(int n)
    {
        switch (n)
        {
            case 0:
                return "Ace";
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
                return (n+1).ToString();
            case 10:
                return "Jack";
            case 11:
                return "Queen";
            case 12:
                return "King";
            default:
                throw new ArgumentException("Unrecognized card value.");

        }
    }

    private string SuitToName(int s)
    {
        switch (s)
        {
            case 0:
                return "Clubs";
            case 1:
                return "Diamonds";
            case 2:
                return "Spades";
            case 3:
                return "Hearts";
            default:
                throw new ArgumentException("Unrecognized card suit");
        }
    }

    public int CompareTo(PlayingCard other)
    {
        int result = this.Suit.CompareTo(other.Suit);

        if (result != 0)
            return result;

        return this.Value.CompareTo(other.Value);
    }

    public override string ToString()
    {
        return String.Format("{0} of {1}", ValueName, SuitName);
    }
}

It has all the comparison and value conversion coded within it, so you don't have to worry about creating highly specialized methods to do extraneous conversions. You can use it in a deck like so:

Array Implementation

// How to initialize deck
PlayingCard[] deck = Enumerable.Range(0, 52)
                        .Select(x => new PlayingCard(x % 13, x / 13, imageListCards[x]))
                        .ToArray();


// How to shuffle deck
Random r = new Random();
Array.Sort(deck, (a, b) => r.Next(0, 2) == 0 ? -1 : 1);

// How to reset deck
Array.Sort(deck);

// How to display top five cards
pictureBox_Card1.Image = deck[0].CardImage;
pictureBox_Card2.Image = deck[1].CardImage;
pictureBox_Card3.Image = deck[2].CardImage;
pictureBox_Card4.Image = deck[3].CardImage;
pictureBox_Card5.Image = deck[4].CardImage;

List Implementation

// How to initialize deck
List<PlayingCard> deck = Enumerable.Range(0, 52)
                        .Select(x => new PlayingCard(x % 13, x / 13, imageListCards[x]))
                        .ToList();


// How to shuffle deck
Random r = new Random();
deck.Sort((a, b) => r.Next(0, 2) == 0 ? -1 : 1);

// How to reset deck
deck.Sort();

// How to display top five cards
pictureBox_Card1.Image = deck[0].CardImage;
pictureBox_Card2.Image = deck[1].CardImage;
pictureBox_Card3.Image = deck[2].CardImage;
pictureBox_Card4.Image = deck[3].CardImage;
pictureBox_Card5.Image = deck[4].CardImage;

EDIT:

Manual Shuffling

If you want to do a shuffle manually, there's a simple algorithm called the Fisher-Yates Shuffle that will do the trick:

private static Random r = new Random();
static void Shuffle<T>(T[] array)
{
    for (int i = 0; i < array.Length; i++)
    {
        int idx = r.Next(i, array.Length);
        T temp = array[idx];
        array[idx] = array[i];
        array[i] = temp;
    }
}

(List Implementation)

private static Random r = new Random();
static void Shuffle<T>(List<T> list)
{
    for (int i = 0; i < list.Count; i++)
    {
        int idx = r.Next(i, list.Count);
        T temp = list[idx];
        list[idx] = list[i];
        list[i] = temp;
    }
}

相关问答

更多
  • 在你的建筑设置卡片中留下52个。然后当你处理一张卡片时,将该数字减去一个 public card deal() { if ( currentCard < NCARDS ) { cardsLeft--; return ( deckOfCards[ currentCard++ ] ); } else { System.out.println("Out of cards error"); return ...
  • 它应该有一个与数组平行的数组,指示卡是否已从卡组中移除。 短语“表示是否”是需要布尔值的赠品。 在你的情况下,这是一个包含52个布尔值的数组,所以bool is_removed[52]; 。 [...]如何检查是否从原始阵列中删除了某些内容? 您不想检查是否从原始数组中删除了某些内容,因为您实际上并不想从原始数组中删除任何内容。 永远。 相反,要从卡组中删除卡,只需将is_removed[i]设置为true (其中i是适当的索引); 并检查卡片是否已从卡座中移除,您只需检查is_removed[i] 。 I ...
  • 在java中,方法main()是代码开始运行的地方。 您现在的主要方法中没有任何内容: public static void main(String[] args) {} 要让它做某事,将其更改为以下内容: public static void main(String[] args) { deck myDeck = new deck(); myDeck.create(); myDeck.shuffle(); } 作为一个注释,在java中使用大写字母命名您的类是很好的做法。 In java, th ...
  • 一种选择是从一个包含所有卡片的完整数组列表开始,然后删除一个随机索引,直到列表为空,此时您将重新填充它。 例: ArrayList list = new ArrayList(); for(int i=0;i<52;i++){ list.add(i+1); } int c = 52; Random random = new Random(); while(c>0){ int r = random.nextInt(c--); int card = li ...
  • 我不确定您的PlayingCard类是如何编码的,但您的问题似乎有很大一部分来自其设计。 以这个实现为例: PlayingCard类 public class PlayingCard : IComparable { private int value; private int suit; private Bitmap cardImage; public int Value => value; public string ValueName ...
  • List shuffledDeck = new List (); while (myDeck.Count > 0) { int c = myDeck.Count; int n = rNumber.Next (0, c); var value = myDeck[n]; shuffledDeck.Add(value); myDeck.Remove(value); } 您需要确保没有比实际数组对象计数更多 ...
  • 您没有构建4个列表,您正在构建一个列表,引用4次: hands = Nplayers*[[]] 乘以列表不会创建值的副本; 而是仅复制参考 ; 追加hands[0]将反映在同一列表的所有其他引用中。 使用列表理解: hands = [[] for _ in range(Nplayers)] 使用切片最容易: def deal_cards(deck, Nplayers): shuffle(deck) l = len(deck) portion = l // Nplayers ...
  • 不,代码不符合您的要求。 Dim Cards(52) As Integer 这将为53张卡而不是52张创建一个数组。使用: Dim Cards(51) As Integer 在洗牌时,将每张卡片更换为卡片(或其本身)中较早的卡片,而不是卡片中的任何位置。 (这是Fisher-Yates洗牌的原则。) 不要将计数器与循环分开,而是使用计数器进行循环。 Dim rand = New Random() For counter = 0 to Cards.Length - 1 Dim n = rand.N ...
  • 我相信问题可能是你错过了Rnd返回0(包括)和1(不包括)之间的值,这意味着当转换为整数时,它将永远不会返回上限值。 因此,您需要将上限扩展为52,以确保最终“找到”索引#51。 您还可以通过仅在找到下一个空索引后分配第q张卡来保存一些工作,并且我相信只需一次种植Randomize就足够了: Dim q As Integer Dim dealrand As Integer Dim dealused = Enumerable.Range(0, 52).Select(Function(x ...
  • 卡组是卡的阵列(或列表或其他有序集)。 你如何代表每张卡取决于你; 可能只是一个int取模13的值和int除以4为西装,或可能是一个对象。 Shuffling随机化了该数组或列表的顺序。 最简单的shuffle可能是(伪代码,假设deck被声明为Card []): for(int i=0;i

相关文章

更多

最新问答

更多
  • python的访问器方法有哪些
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。
  • 响应navi重叠h1和nav上的h1链接不起作用(Responsive navi overlaps h1 and navi links on h1 isn't working)
  • 在C中读取文件:“r”和“a +”标志的不同行为(Reading a File in C: different behavior for “r” and “a+” flags)
  • NFC提供什么样的带宽?(What Kind of Bandwidth does NFC Provide?)
  • 元素上的盒子阴影行为(box-shadow behaviour on elements)
  • Laravel检查是否存在记录(Laravel Checking If a Record Exists)
  • 设置base64图像的大小javascript - angularjs(set size of a base64 image javascript - angularjs)
  • 想学Linux 运维 深圳有哪个培训机构好一点
  • 为什么有时不需要在lambda中捕获一个常量变量?(Why is a const variable sometimes not required to be captured in a lambda?)
  • 在Framework 3.5中使用服务器标签<%=%>设置Visible属性(Set Visible property with server tag <%= %> in Framework 3.5)
  • AdoNetAppender中的log4net连接类型无效(log4net connection type invalid in AdoNetAppender)
  • 错误:发送后无法设置标题。(Error: Can't set headers after they are sent. authentication system)
  • 等待EC2实例重启(Wait for an EC2 instance to reboot)
  • 如何在红宝石中使用正则表达式?(How to do this in regex in ruby?)
  • 使用鼠标在OpenGL GLUT中绘制多边形(Draw a polygon in OpenGL GLUT with mouse)
  • 江民杀毒软件的KSysnon.sys模块是什么东西?
  • 处理器在传递到add_xpath()或add_value()时调用了什么顺序?(What order are processors called when passed into add_xpath() or add_value()?)
  • sp_updatestats是否导致SQL Server 2005中无法访问表?(Does sp_updatestats cause tables to be inaccessible in SQL Server 2005?)
  • 如何创建一个可以与持续运行的服务交互的CLI,类似于MySQL的shell?(How to create a CLI that can interact with a continuously running service, similar to MySQL's shell?)
  • AESGCM解密失败的MAC(AESGCM decryption failing with MAC)
  • SQL查询,其中字段不包含$ x(SQL Query Where Field DOES NOT Contain $x)
  • PerSession与PerCall(PerSession vs. PerCall)
  • C#:有两个构造函数的对象:如何限制哪些属性设置在一起?(C#: Object having two constructors: how to limit which properties are set together?)
  • 平衡一个精灵(Balancing a sprite)
  • n2cms Asp.net在“文件”菜单上给出错误(文件管理器)(n2cms Asp.net give error on Files menu (File Manager))
  • Zurb Foundation 4 - 嵌套网格对齐问题(Zurb Foundation 4 - Nested grid alignment issues)
  • 湖北京山哪里有修平板计算机的