通过 jquery 为新创建的元素添加属性

Add attribute to newly created element by jquery

本文关键字:元素 添加 属性 创建 jquery 新创建 通过      更新时间:2023-09-26
$(document).on('click', "#mybusi_radio", function(){
   alert("Script test");
   $(document).("#mybusi_radio").attr("checked", "checked");
});

我正在尝试将"选中","已检查"属性添加到输入无线电元素。 此元素在页面加载后由某些脚本创建。 警报正在工作。 如何向此输入元素添加属性。 请帮助

您可以使用

$(document).on('click', "#mybusi_radio", function () {
    $(this).prop("checked", true);
});

而不是

$(document).("#mybusi_radio").attr("checked", "checked"); 

$("#mybusi_radio").prop("checked",true); 

问题是选择器:

$(document).("#mybusi_radio").attr("checked", "checked");

首先,选择document,然后提供一个参数 '#mybusi_radio' 但不提供应将该参数传递给的命名方法;因此存在语法错误。

您是否对其进行了编辑以提供适当的方法,例如 find() ,以提供:

$(document).find('#mybusi_radio').attr('checked', 'checked');

这将(似乎1(起作用。

这种方法的问题在于,您要在整个文档中搜索已在on()方法的匿名函数中引用的元素:它是this(DOM 节点(或$(this)(包含 DOM 节点的 jQuery 对象(。

此外,您正在对click事件做出反应,该事件将捕获对元素本身的点击,但不会对用户单击关联的<label>元素做出反应;所以我建议改用change事件来提供:

$(document).on('change', "#mybusi_radio", function () {
    $(this).prop("checked", true);
});

或者,为了避免在 DOM 节点完全足以满足此用例时使用不必要的 jQuery:

$(document).on('change', "#mybusi_radio", function () {
    this.checked = true;
});

但这有点奇怪,因为您有效地阻止了用户更改元素的checked/非checked状态,或者不必要地将其设置为checked,而这将是元素的默认行为(假设它确实是类型 radio<input>(。

重新阅读您的问题后,您似乎正在向页面添加一个元素(以某种方式(并希望将其初始状态设置为 checked ?如果这确实是用例,那么您可以简单地在元素创建时设置元素的状态(如果您选择向我们展示创建和附加相关元素的脚本,这将对您更有用(:

// creates an <input> element:
$('<input />', {
    // sets the 'type' attribute/property to 'radio':
    'type' : 'radio',
    // sets the id of the <input> to
    // 'mybusi_radio':
    'id' : 'mybusi_radio',
    // sets the 'checked' property to true
    // Boolean (not a string):
    'checked' : true
// appends the created <input> to the element
// identified by its id, of 'parentElementID':
}).appendTo('#parentElementID');

  1. 由于 attr() 不会专门更新元素的基础属性,因此当您可能会惊讶地发现已检查的无线电输入表现为未经检查的无线电输入时,您可能会发现 checked 属性稍后不会在代码中更新/反映。因此,如果您使用的是支持 prop() 2 的 jQuery 版本,最好使用 prop()
  2. jQuery 1.6 及更高版本,因此您应该使用支持/实现prop()的 jQuery 版本。

引用:

  • appendTo() .
  • attr() .
  • find() .
  • prop() .