如何更改动态生成的文本框的颜色

时间:2015-10-25 08:30:47

标签: javascript php jquery

我在单击事件时更改动态生成的文本框的颜色时遇到困难。我们的想法是,如果用户想要更新文本框中的文本,则应更改文本框的颜色。 这是我的代码: 以下代码实际上从数据库中提取数据并将其显示给用户

echo '<td>'.
     '<input type = "text" class="form-control" onclick="changeColor()" disabled = "disabled" 
     id ="'.$row["ID"].'"  name = "fieldText['.$row["ID"].
     ']" value = "'.$row["fieldText"].'">'."</td>";

在Click事件中,我想更改文本框的颜色, 这是我的尝试:

changeColor () { this.style.color = '#cc0000'; }

我已将此代码集成到上面一行,但是它给了我一个错误。

  

错误:TypeError:无法设置未定义的属性'color'

4 个答案:

答案 0 :(得分:1)

更改事件处理程序以将当前上下文this发送到事件处理程序。

onclick="changeColor(this)"

在JS中使用元素上下文并在其上设置属性。

function changeColor (el) {
    el.style.color = '#cc0000';
}

我建议使用class而不是设置内联样式。

CSS:

.warning {
    color: #c00;
}

JS:

el.classList.add('warning');

由于jQuery包含在页面中,我建议使用它来绑定事件。

$('input.form-control').on('click', function() {
    $(this).addClass('warning');
});

更改焦点上元素的颜色

input:focus, input:active {
    border-color: #c00;
}

答案 1 :(得分:1)

您可以通过绑定到输入上的click事件并删除内联onClick() ...来简化它。

$('input').on('click', function(){

    $(this).css({ 'border': '1px solid black', 'background-color': 'white' });
})

通过使用'data-'属性,您可以隔离要绑定的输入...

<input data-myattribute="" blah blah blah />

然后你可以使用

$(document).on('click', 'input[data="myattribute"]', function(){

    $(this).css({ 'border': '1px solid black', 'background-color': 'white' });
})

编写后续问题

HTML

<button id="update">Update</button>

JS

$('#update').on('click', function(){

    // Gets the input elements you're interested in
    var items = $(document).find('input[data="myattribute"]');
    // Loops through each jQuery object and you can apply whatever property values you want
    items.each(function(){
        $(this).css({ 'border': '1px solid blue', 'background-color': 'red' });
    });

});

答案 2 :(得分:0)

首先为您的输入提供一个课程,可能是Txt1

如果您想在click()

上执行此操作
echo '<td>'.'<input type = "text" class="form-control Txt1" onclick="changeColor()" disabled = "disabled" id ="'.$row["ID"].'"  name = "fieldText['.$row["ID"].']" value = "'.$row["fieldText"].'">'."</td>";

风格

.background{
     background-color : #90EE90;
}

脚本

$(document).ready(function() {

  $(document).on("click",".Txt1",function() {
   $(this).addClass('background');
 });

 $(document).on("blur",".Txt1",function() {
   $(this).removeClass('background');
 });

});

如果你想要焦点(),改变这样的代码,

$(document).on("focus",".Txt1",function() {

这是工作fiddle

答案 3 :(得分:0)

为了从动态生成的元素中获取事件,您需要将事件开始与文档对象绑定。

e.g。

$(document).on("click",".className or #id" ,function(e){
});

对于输入类型,请根据您的要求使用模糊事件或点击事件

$(document).on("click/blur","input[type="text"],function(e){
    $(this).css({'color': '#cc0000});
});